mybatis 關聯關係對映 一對多 ,多對多

2021-09-05 01:31:59 字數 2432 閱讀 8264

一對多 ,用order訂單表,orderitem訂單項 來舉例

1.將資料表匯入資料庫中

3.修改order,orderitem實體類,建立實體對映關聯關係(一對多、多對一)

#一對多:乙個訂單對應多個訂單項

private listorderitems=new arraylist<>();

#一對一:乙個訂單項對應乙個訂單

private order order;

4.配置mybatis關聯對映 

select

*from t_hibernate_order o,t_hibernate_order_item oi

where o.order_id=oi.oid and o.order_id=#

select

* from t_hibernate_order o,t_hibernate_order_item oi

where o.order_id=oi.oid and oi.order_item_id=#

5.   建立orderserver    orderserverimpl       ordreitemserver    ordreitemserverimpl 

測試   

一對多 

package com.zking.ssm.service.impl;

import com.zking.springjunitbasetest;

import com.zking.ssm.model.order;

import com.zking.ssm.service.orderserver;

import org.junit.test;

import org.springframework.beans.factory.annotation.autowired;

import static org.junit.assert.*;

/** * @author hyt

* @site

* @company

* @create  2018-12-21 11:06

*/public class orderserverimpltest extends springjunitbasetest

}

結果:

一對一

package com.zking.ssm.service.impl;

import com.zking.springjunitbasetest;

import com.zking.ssm.model.orderitem;

import com.zking.ssm.service.orderitemserver;

import org.junit.test;

import org.springframework.beans.factory.annotation.autowired;

import static org.junit.assert.*;

/** * @author hyt

* @site

* @company

* @create  2018-12-21 11:51

*/public class orderitemserverimpltest extends springjunitbasetest

}

執行結果:

多對多, 用hbook書籍表,category書籍類別表 以及中間表bookcategory來舉例

一本書對應多個類別,乙個類別對應多本書

前面步驟一樣

select *

from t_hibernate_book b,t_hibernate_category c,t_hibernate_book_category bc

where b.book_id=bc.bid and bc.cid=c.category_id and b.book_id=#

select *

from t_hibernate_book b,t_hibernate_category c,t_hibernate_book_category bc

where b.book_id=bc.bid and bc.cid=c.category_id and c.category_id=#

之後測試也是一樣一樣的 ,可以得到想要的結果

Hibernate 一對多 關聯關係對映

維護關係為 一指向多的關係,在載入一的時候可將多的一端資料自動載入 班級和學生就是一對多的關係 單向關聯 學生端 name com.bjpowernode.hibernate.student table t student name id class native id name name clas...

Mybatis 一對一關係對映

一對一關係 使用人和身份證為例 實體類 person端 用這一端來維護關係 private integer id private string name private integer cid private card card 生成對應的set,get方法 card端 private intege...

MyBatis高階對映之 一對一(一對多)關聯對映

在hibernate中可以進行一對一,多對一,一對多,多對多,mybatis中也可以實現這種對映,但是對映就顯得比較麻煩了,下面看乙個一對一的例子,學了hibernate都知道其實一對一跟一對多的原理其實是一致的,所以也是一對多的例子 首先配置sqlmapconfig.xml public conf...