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.

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