Mybatis处理多个多对一的关系

图书与图书类型是多对一关系,图书与管理员也是多对一关系
先看一下数据库关系:
Admin表:
在这里插入图片描述
BookType表:
在这里插入图片描述
Book表:
在这里插入图片描述
对应实体类:

public class Admin {
	private Integer aid;
	private String username;
	private String name;
	private String pwd;
	private String phone;
	private Integer state;
	// 省略get、set 
}

public class BookType {
	private Integer typeid; //图书类型编号
	private String typename;	//图书类型名称
	// 省略get、set 
}

public class Book implements Serializable{
	private Integer bookid;	//图书编号
	private String isbn;//ISBN 国际标准书号
	private BookType booktype;	//图书类型
	private String bookname;	//图书名称
	private String autho;	//作者名称
	private String press;	//出版社
	private Date putdate;	//上架日期
	private Integer num;	//总数量
	private Integer currentnum;	//在馆数量
	private Double price;	//价格
	private String description;	//简介
	private Admin admin;	//操作管理员
	// 省略get、set 
}

对应实体类中注意Book类中的BookType和Admin的关系(为多对一关系)

<?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="com.hsc.mapper.BookMapper" >

    <!-- 图书:图书类型 ==  多对一 -->
    
    <select id="selectBookType" resultType="BookType">
    	select typeid typename from booktype where typeid = #{oo}
    </select>
    
    <select id="selectAdmin" resultType="Admin">
    	select aid username,name,pwd,phone,state from admin where aid = #{pp}
    </select>
    
    <resultMap type="Book" id="bookMap">
    	<id column="bookid" property="bookid"/>
    	<result column="isbn" property="isbn"/>
    	<result column="bookname" property="bookname"/>
    	<result column="autho" property="autho"/>
    	<result column="press" property="press"/>
    	<result column="putdate" property="putdate"/>
    	<result column="num" property="num"/>
    	<result column="currentnum" property="currentnum"/>
    	<result column="price" property="price"/>
    	<result column="description" property="description"/>
    	<association property="booktype" javaType="BookType"
    				 column="typeid"
    				 select="selectBookType"/>
    	<association property="admin" javaType="Admin"
    				 column="aid"
    				 select="selectAdmin"/>
    </resultMap>
    
	<select id="selectBookByPage" resultMap="bookMap">
		select bookid,isbn,bookname,typeid,autho,press,putdate,num,currentnum,price,description,aid
		from book
	</select>
	
</mapper>

使用两个association 标签即可,这里使用的是常用的多对一单表查询,其中#{oo}和#{pp}可以随意命名,但是不能为空。经过测试结果OK.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章