ssm初战问题记录(一)——MyBatis对对象嵌套对象的查询

自定义了一个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中虽然有对应条数的记录,但是并没有存储相应的内容。最后发现是包含关系的这两个对象作为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项目初战)