如何将枚举的List
用作Mybatis查询的参数?我已经为其创建了一个类型处理程序,并按照其他问题指定了映射类型。当应该为数千时,它正在返回0计数。
@Mapper
public interface BadgeMapper {
@Select("select count(*) from badges where appType in (#{appTypes})")
int countByType(@Param("appTypes") List<AppType> appTypes);
package com.example.mapper;
@MappedTypes({AppType.class})
public class AppTypeTypeHandler implements TypeHandler<AppType> {
@Override
public void setParameter(PreparedStatement ps, int i, AppType parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, parameter.toString()); // use toString not name()
}
public static enum AppType {
ANDROID("A", "Android"), THEME("T", "Theme"), ...
private String val;
private String desc;
AppType(String v, String d) { val = v; desc = d; }
public String toString() {
return val;
}
application.properties
mybatis.type-handlers-package=com.example.mapper
调试日志似乎显示正确的值('a','t','st'),但为计数打印0。
System.out.println(badgeMapper.countByType(appTypes));
Console
c.s.s.mapper.BadgeMapper.countByType : ==> Preparing: select count(*) from badges where appType in (?)
c.s.s.mapper.BadgeMapper.countByType : ==> Parameters: [A, T, ST](ArrayList)
0
MySQL
mysql> select count(*) from badges where appType in ('A', 'T', 'ST');
+----------+
| count(*) |
+----------+
| 2365 |
mybatis xml的参考文档:http://www.mybatis.org/mybatis-3/configuration.html#typehandlers
问题是您键入处理程序根本不被调用。
首先,整个列表被视为一个整体,并将其作为JDBC准备的陈述的一个参数处理。这意味着未通过您指定的类型处理程序来处理单个元素。
没有便携式方法可以将列表设置为JDBC中的IN
准备的语句参数,因此在Mybatis中(如果您使用Postgres,则有多种方法)。
如果您使用的是PostgreSQL,则可以创建一个类型处理程序,该处理程序将接受枚举列表并使用上述问题中描述的方法进行设置。
在一般情况下,您需要动态生成查询以分别处理每个值:
@Select("<script>select count(*) from enu " +
" where appType in ( " +
"<foreach item='appType' collection='appTypes' separator=','>" +
" #{appType,typeHandler=AppTypeTypeHandler}" +
"</foreach>)</script>")
int countByType(@Param("appTypes") List<AppType> appTypes);
另外,您可以使用@SelectProvider
并使用Java代码构建查询。