mybatis3.2.6
注解@Result
设置映射关系,使用one=@One
报错。
一开始目标从数据库文章表获取数据,一篇文章对应一个用户,一篇文章对应一个分类。从文章表获取的user_id
要在到用户表中获取用户信息。
文章类article
public class Article implements Serializable {
private int id;
private String title;
private String content;
private String createTime;
//一个标签对应多个文章
private Tag tag;
//一个用户对应多个文章
private User user;
...
}
User
类
public class User implements Serializable {
private int id;
private String loginname;
private String password;
private String username;
private String email;
private String createTime;
...
}
ArticleDao
:
@SelectProvider(type = ArticleDynaSqlProvider.class, method = "selectWithUserId")
@Results({
@Result(id = true, column = "id", property = "id"),
@Result(column = "title", property = "title"),
@Result(column = "content", property = "content"),
@Result(column = "create_time", property = "createTime"),
@Result(column = "user_id", property = "user", jdbcType = JdbcType.INTEGER,
one = @One(select = "com.sweat.dao.UserDao.selectById")),
@Result(column = "tag_id", property = "tag",
one = @One(select = "com.sweat.dao.TagDao.selectTagWithId"))
})
List<Article> selectWithUserId(Map<String, Object> param);
one = @One(select = "com.sweat.dao.UserDao.selectById"))
对应UserDao
的selectById
方法
@Select("select * from " + BlogConstants.USERTABLE + " where id = #{id}")
User selectById(int id);
TagDao
类似。
ArticleDynaSqlProvider
的selectWithUserId
方法
public String selectWithUserId(final Map<String, Object> params) {
String sql = new SQL(){
{
SELECT("*");
FROM(BlogConstants.ARTICLETABLE);
if(params.get(BlogConstants.USERSESSION) != null) {
User user = (User) params.get(BlogConstants.USERSESSION);
WHERE(" user_id = #{user.id} ");
}
ORDER_BY(" create_time desc ");
}
}.toString();
return sql;
}
一切看着都很正常。
然后调用ArticleDao
的selectWithUserId
方法:
访问URL
报错
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.sweat.dao.ArticleDao.selectWithUserId
当时非常奇怪为什么会报错,各种尝试,后来发现one=@One()
部分有问题。 百度没有查到什么,然后谷歌也没有任何相关的。= =!
后来重新创建个项目,继续使用one=@One
,然后报错
Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: org.apache.ibatis.builder.BuilderException: Cannot use both @One and @Many annotations in the same @Result
很惊讶错误变了,查了一下这个错误,就查到一篇 MyBatis 3.2.6 not work annotation @One #167,发现是这个版本的bug
,然后将2个项目的mybatis
版本都切换到 3.3.0
后(代码没有改),成功运行。
= =。。。 前前后后花了很久时间。