一、實體層設計java
Book.java —— 多sql
public class Book{mybatis
private String id;app
private String bookName;spa
private String userId;設計
private User user; xml
...................................//Getter AND Setterci
}get
User.java——一io
public Class User{
private String id;
private String name;
private List<Book> bookList;
................................//Getter AND Setter
}
二、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 !"".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>
三、DAO層調用
根據用戶名查詢數據
User user = new User();
user.setName("....");
userList = sqlSession.selectList("User.queryUserList",user);
List<Book> bookList = userList.get(0).getBookList(); //查詢到的用戶全部的書籍