Mybatis的一对多和多对一
MyBatis 创建时的一个思想是:数据库不可能永远是你所想或所需的那个样子。 我们希望每个数据库都具备良好的第三范式或 BCNF 范式,可惜它们并不都是那样。 如果能有一种数据库映射模式,完美适配所有的应用程序,那就太好了,但可惜也没有。 而 ResultMap 就是 MyBatis 对这个问题的答案。
比如在user这个类里面有一个book类的对象,表示学生借的书,由于一个学生可以借多本书,所以学生与书的关系就是多对一的关系,而学生表中只有的id,此时如何从数据库取出book的对象,此时我们就需要用到association
resultMap 元素有很多子元素和一个值得深入探讨的结构。 下面是resultMap 元素的概念视图。
结果映射(resultMap)
association – 一个复杂类型的关联;许多结果将包装成这种类型
嵌套结果映射 – 关联可以是 resultMap 元素,或是对其它结果映射的引用
collection – 一个复杂类型的集合
嵌套结果映射 – 集合可以是 resultMap 元素,或是对其它结果映射的引用
一对多:
第一种方式:子查询
<select id="getborrow" resultMap="Bookuser">
select bookid from borrow
</select>
<resultMap id="BookStudent" type="pojo.Borrow">
<association property="book" column="bookid" javaType="pojo.Book" select="getbookbyid"></association>
</resultMap>
<select id="getbookbyid" resultType="pojo.Book">
select * from book where id=#{id}
<!--这里的#{id}中除了id可以随便写什么,他是通过第一个子查询传的参数进来的,因为就查询结果就一个-->
</select>
第二种方式:
按结果嵌套处理(联表查询)
<select id="getborrow" resultMap="Bookuser">
select b.* from book b,borrow bo where b.id=bo.bookid
</select>
<resultMap id="BookStudent" type="borrow">
<association property="book" javaType="Book">
<result property="id" column="id"></result>
<result property="bname" column="bname"></result>
<result property="price" column="price"></result>
<result property="author" column="author"></result>
<result property="content" column="content"></result>
</association>
</resultMap>
多对一:
<select id="getuserbooks" resultMap="users">
<!--这一条语句可以查询出所有你需要的结果,即上表的id,number,name,password,ismanager,books然后用collection收集-->
select u.id,u.number,u.name,u.password,u.ismanager,b.id bid,b.* from user u join borrow bo on u.id=bo.borrowid join book b on b.id=bo.bookid where u.id=#{id}
</select>
<resultMap id="users" type="user">
<result property="id" column="id"></result>
<result property="number" column="number"></result>
<result property="name" column="name"></result>
<result property="password" column="password"></result>
<result property="ismanager" column="ismanager"></result>
<collection property="books" ofType="book">
<result property="id" column="bid"></result>
<result property="bname" column="bname"></result>
<result property="price" column="price"></result>
<result property="author" column="author"></result>
<result property="content" column="content"></result>
</collection>
</resultMap>
mybatis1