mybaits 学习笔记(一对多)三

1、实体层设计

  Book.java  —— 多

    public class Book{

      private String id;

      private String bookName;

      private String userId;

      private User user; 

      ...................................//Getter AND Setter

    }

  

  User.java——一

    public Class User{

      private String id;

      private String name;

           private List<Book> bookList;

      ................................//Getter AND Setter

    }

 

2、XML文件配置

  User.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="User">

<resultMap type="bean.User" id="User">
<id column="u_id" jdbcType="INTEGER" property="id"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<collection property="bookList" resultMap="Book.BookResult"></collection>
</resultMap>

<select id="queryUserList" parameterType="bean.User" resultMap="User">
select u.id u_id, u.name,b.id,b.book_name,b.user_id from user u left join book b on
u.id = b.user_id
<where>
<if test="name != null and !&quot;&quot;.equals(name.trim())">
and a.name=#{name}
</if>
</where>
</select>

</mapper>

 

Book.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="Book">

<resultMap type="bean.Book" id="BookResult">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="book_name" jdbcType="VARCHAR" property="bookName"/>
<result column="user_id" jdbcType="VARCHAR" property="userId"/>

<association property="user" resultMap="User"></association>
</resultMap>

</mapper>

 

3、DAO层调用

    根据用户名查询数据

    User user = new User();

    user.setName("....");

    userList = sqlSession.selectList("User.queryUserList",user);

    List<Book> bookList = userList.get(0).getBookList(); //查询到的用户所有的书籍

     

    

  

  

posted @ 2017-12-14 12:58  寂寞有害  阅读(166)  评论(0编辑  收藏  举报