我正在学习如何使用MyBatis。老实说,我非常喜欢这个框架。它易于使用,我对它很满意,因为我可以使用我的 sql 命令:) 我使用 MyBatis 3.4.2 和 PostgreSQL 数据库。
例如,我喜欢在插入@SelectKey
注释之前执行查询是多么容易。如果我在接口方法之前添加一些注释,数据映射就像一个魅力,就像这样:@Results({ @Result(property = "javaField", column = "database_field", javaType = TypeHandler.class)
.
我不喜欢的(我希望你能把我引向正确的方向)如下:
(问题 1)我有一些查询允许我使用 null 和正常值,而无需任何额外的“if”java 语句来检查变量是否包含 null 值。它们看起来像这样:
SELECT * FROM table
WHERE key_name = ? AND ((? IS NULL AND user_id IS NULL) OR User_id = ?)
使用 JDBC,我需要执行以下操作:
stmt = connection.prepareStatement(query);
stmt.setString(1, "key");
stmt.setString(2, userId);
stmt.setString(3, userId);
如您所见,我需要传递两次userId,因为这是 JDBC 的工作方式。老实说,我的期望是下面的代码可以与 MyBatis 一起使用,但不幸的是它不起作用。第三个参数仍然需要定义。
我想知道是否可以将这个功能添加到 MyBatis 中。如果 MyBatis 可以自动绑定两次userId应该没问题,如下所示:
@Select("SELECT * FROM table key_name = #{key} and ((#{userId} is null and user_id is null) OR user_id = #{userId})
SomeClass findByKeyAndUserId(String key, Long userId);
我实际做的解决方法如下。我讨厌它,因为它很棘手,并且需要额外的 java "if" 语句:
@Select("SELECT * FROM table WHERE key_name = #{key} AND COALESCE(user_id, -1) = #{userId}")
SomeClass findByKeyAndUserId(String key, Long userId);
userId = (userId == null) ? -1 : userId;
SomeClass abc = mapper.findByKeyAndUserId(key, userId);
我不知道用 MyBatis 管理这种情况的最佳做法是什么。请指导我。
(问题 2)在@Select
. 在映射具有相同结果类型的查询结果时,有什么方法可以避免重复代码?
第一个查询:
@Select("SELECT * FROM table WHERE ...")
@Results({
@Result(property = "key", column = "key_name", javaType = String.class),
@Result(property = "value", column = "key_value", javaType = String.class),
@Result(property = "userId", column = "user_id", javaType = Long.class),
@Result(property = "interval", column = "interval", javaType = Long.class),
@Result(property = "description", column = "description", javaType = String.class),
@Result(property = "status", column = "status", typeHandler = StatusTypeHandler.class)
})
SomeClass findByKeyAndUserId(@Param("key") String key, @Param("userId") Long userId);
第二个查询:
@Select("SELECT * FROM table WHERE <different conditions then before>")
@Results({
<I need to add here the exact same code then before in query 1>
})
SomeClass findByKeyAndUserId(@Param("key") String key, @Param("userId") Long userId);
我可以以某种方式重用与映射相关的代码吗?我需要添加映射,因为我对状态字段使用特殊类型的处理程序。我使用基于注释的配置。
(问题 3) @Param
注释我在文档中看不到任何关于@Param
注释的内容。这很难弄清楚为什么我的 java 参数没有正确限制。最后我意识到@Param
我的代码中缺少注释。为什么官方文档中没有提到这一点?我以错误的方式做某事并且@Param
没有必要使用?
该代码工作正常:
SomeClass findByKeyAndUserId(@Param("key") String key, @Param("userId") Long userId);
这不起作用:
SomeClass findByKeyAndUserId(String key, Long userId);
更新(问题 1)
我的第一个想法与@blackwizard提到的类似:“Mybatis 确实按名称绑定参数,然后一次、两次、N 次,只要它被引用,它就可以工作。”
但这实际上不能正常工作。如果 userId 不为空,它会起作用。如果它为空,我会得到一个从数据库返回的很好的异常。我猜 MyBatis 以错误的方式绑定 null 值。也许这是一个错误。我不知道 :(
例外:
org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.postgresql.util.PSQLException: ERROR: could not determine data type of parameter $2
### The error may exist in com/.../dao/TableDao.java (best guess)
### The error may involve ....dao.Table.findByKeyAndUserId-Inline
### The error occurred while setting parameters
### SQL: SELECT * FROM table WHERE key_name = ? AND (? IS NULL AND user_id IS NULL) OR user_id = ? AND status = 1
### Cause: org.postgresql.util.PSQLException: ERROR: could not determine data type of parameter $2
最后我找到了三种不同的解决方案。
(问题1:解决方案1)
我遵循@blackwizard提到的内容,并且能够将条件userId = (userId == null) ? -1 : userId
从 java 移动到 MyBatis 级别。而且还不错!正确的语法是:<if test='userId==null'><bind name='userId' value='-1'/></if>
.
(问题1:解决方案2)
我从postgres返回错误的原因could not determine data type of parameter $2
是因为在空值的情况下,JDBC驱动程序无法确定参数的类型。所以让我们手动定义它。
@Select("SELECT * FROM table "
+ "WHERE key_name = #{key} AND ((#{userId}::BIGINT IS NULL AND user_id IS NULL) OR user_id = #{userId})")
})
SomeClass findByKeyAndUserId(@Param("key") String key, @Param("userId") Long userId);
(问题1:解决方案3) 第二种解决方案依赖于PorstgreSQL。以下解决方案完全独立于数据库。感谢@blackwizard 的精彩评论。
@Select("SELECT * FROM table "
+ "WHERE key_name = #{key} AND ((#{userId, jdbcType=BIGINT} IS NULL AND user_id IS NULL) OR user_id = #{userId})")
})
SomeClass findByKeyAndUserId(@Param("key") String key, @Param("userId") Long userId);
我个人更喜欢解决方案 3。它包含的附加代码较少。