自定义了一个Book类,其中有一个属性为自定义的Category类,两个类的定义如下public class Book { private int id; private String isbn; private String title; private Category category; private String author; BigDecimal price;
//Constructors,Setters And Getters
}
public class Category { private static final long serialVersionUID = 1L; private int id; private String name;
//Constructors,Setters And Getters
}
BookDao.xml配置如下
<mapper namespace="dao.BookDao"> <resultMap id="bookResultMap" type="book"> <id column="id" property="id" javaType="java.lang.Integer"/> <result property="isbn" column="isbn"/> <result property="title" column="title"/> <result property="author" column="author"/> <result property="price" column="price"/> <association property="category" javaType="category"> <id property="id" column="id"/> <result property="name" column="name"/> </association> </resultMap> <select id="getAllBooks" resultMap="bookResultMap"> SELECT b.*,c.* FROM yuehu.book_t b,yuehu.category_t c WHERE b.category = c.category_id </select> </mapper>
结果发现虽然没有报错,但是在页面中getAllBooks返回的内容并没有显示。调试查看发现getAllBooks()方法返回的List<Book>中虽然有对应条数的记录,但是并没有存储相应的内容。最后发现是包含关系的这两个对象作为id的属性在数据库表中对应的column名不能相同。修改数据库,并将BookDao.xml文件修改如下后问题解决
<resultMap id="bookResultMap" type="book"> <id column="book_id" property="id" javaType="java.lang.Integer"/> <result property="isbn" column="isbn"/> <result property="title" column="title"/> <result property="author" column="author"/> <result property="price" column="price"/> <association property="category" javaType="category"> <id property="id" column="category_id"/> <result property="name" column="name"/> </association> </resultMap>
本文记录了在使用SSM框架时遇到的MyBatis对对象嵌套对象查询的问题。在页面上,getAllBooks方法返回的列表虽然有正确数量的记录,但内容为空。经过调试发现,由于数据库表中两个对象作为id的属性column名相同导致。通过修改数据库表结构和BookDao.xml文件,问题最终得到解决。
3306

被折叠的 条评论
为什么被折叠?



