雙向一對多

2022-03-27 15:34:58 字數 2584 閱讀 5209

雙向一對多是many-to-one的雙方都有用註解來維持關聯關係;

many的一方:

@joincolumn(name="d_id")

@manytoone(fetch=fetchtype.lazy)

private dept dept;

one的一方:

//一對多關聯

@joincolumn(name="d_id")

@onetomany

private setempset;

注意:雙方的關聯關係的@joincolumn註解裡的name屬性規定的外鍵名必須一樣;例如這裡都為 d_id;

1.插入

**:@test

public void testinsert()

結果:hibernate:

insert

into

tb_emp

(birthday, d_id, name, salary)

values

(?, ?, ?, ?)

hibernate:

insert

into

tb_emp

(birthday, d_id, name, salary)

values

(?, ?, ?, ?)

hibernate:

insert

into

tb_dept

(dname)

values

(?)hibernate:

update

tb_emp

setbirthday=?,

d_id=?,

name=?,

salary=?

where

id=?

hibernate:

update

tb_emp

setbirthday=?,

d_id=?,

name=?,

salary=?

where

id=?

hibernate:

update

tb_emp

setd_id=?

where

id=?

hibernate:

update

tb_emp

setd_id=?

where

id=?

可以看出:如果先儲存many的一端,後儲存one的一端,會多出4條update語句;

因為兩邊都維護關聯關係;先儲存emp,由於此時還沒有dept,所以沒有外來鍵;

dept插入後,由dept維護關聯關係,發出兩條update語句,給emp加上外來鍵;

emp自身也要維護關聯關係,也發出兩條update語句;

如果先插入one的一方後插入many的一方則只會多出兩條update語句;

這是由於one的一方先插入,many的一方插入時外來鍵已經有了;

one的一方為了維護關聯關係會發出兩條update語句;

而many的一方不會再發出update語句;

hibernate:

insert

into

tb_dept

(dname)

values

(?)hibernate:

insert

into

tb_emp

(birthday, d_id, name, salary)

values

(?, ?, ?, ?)

hibernate:

insert

into

tb_emp

(birthday, d_id, name, salary)

values

(?, ?, ?, ?)

hibernate:

update

tb_emp

setd_id=?

where

id=?

hibernate:

update

tb_emp

setd_id=?

where

id=?

在進行雙向一對多關聯關係時,最好只用many的一方來維護關聯關係,這樣可以避免沒有必要的update語句;

注意:此時one的一端的@joincolumn註解必須去掉,不然會報錯;

//一對多關聯

//@joincolumn(name="d_id")

private setempset;

結果:hibernate:

insert

into

tb_dept

(dname)

values

(?)hibernate:

insert

into

tb_emp

(birthday, d_id, name, salary)

values

(?, ?, ?, ?)

hibernate:

insert

into

tb_emp

(birthday, d_id, name, salary)

values

(?, ?, ?, ?)

Hibernate一對多 雙向

hibernate 雙向關聯就是有 一對多 和 多對一 兩個關聯組合而成德,在雙向關聯的兩端都知道對方是誰。下面就開始演示這種關聯。首先定義我們需要使用的pojo物件。public class member public class order 兩個pojo對應的對映檔案分別為member.hbm....

hibernate單向一對多和雙向一對多

單向一對多 例如有部門封裝類 private int deptno private string deptname private string location 有職員封裝類 private int empno private string empname private dept dept 在多...

雙向的多對一或者雙向的一對多

一對多或者多對一都是從一方來看,雙向是從兩個方向來看 這個時候持久化類的一放要有多方的屬性,多方要包含一方的屬性.在對映的檔案當中也是.兩邊都要配置,以便是one to many 另一邊是many to one 在測試方法裡,可以從一方看的方式來查詢,更 一對多多對一的差不多 可以在對映檔案裡配置i...