1. 程式人生 > >hibernate關聯:一對多

hibernate關聯:一對多

  1. 什麼是關聯(association) 關聯指的是類之間的引用關係。如果類A與類B關聯,那麼被引用的類B將被定義為類A的屬性。

    傳統的jdbc要查有關係的兩張表,一般就是同連表查詢 Hibernate就不要需要,它只需要維護實體類,表達清楚表與表之間的關係即可 可以通過get(),它會自動導航把orderIterm也查詢出來了 Session.get(Order.class,1)

2.級聯新增 (1)在實體類中描述表與表之間的關係 注意:定義一對多的關係時一定要採用介面的方式,不能使用實現類

//implements java.util.Set  代理實現的是set介面
	private Set<OrderItem> orderItems=new HashSet<OrderItem>();

關係:一個訂單對應著多個訂單項 一個訂單項對應一個訂單

配置關係: 一對多:

name:實體類的類屬性
    		cascade:用來配置維護實體類之間的關係所用
    		inverse:(inverse="true")關係交由反方控制    即訂單項   因為現在配置的是訂單,所以反方是訂單項
    		(inverse="true") 關係由自己控制   訂單
    		lazy="false":立即載入
    		 -->
    		<set lazy="false" name="orderItems" cascade="save-update" inverse="true">
    			<!-- 訂單項外來鍵 -->
    			<key column="oid"></key>
    			<!-- 一個訂單對應多個訂單項 -->
    			<one-to-many class="com.zking.four.entity.OrderItem"></one-to-many>
    		</set>

多對一: 報錯: Repeated column in mapping for entity; Com.zking.four.entity.OrderIterm column: oid (should be mapped with insert=”false” update=”false”)

重複的列:oid重複 同一個資料庫的欄位被映射了兩次

解決方法: 1:將訂單項實體類中的訂單id這個屬性幹掉 2:在OederIterm的配置檔案中,在oid後面加上 insert=”false” update=”false”,或者在order後面加上 insert=”false” update=”false”

<!-- 第一種加insert=false,update=false -->
    		<property name="oid" type="java.lang.Integer" column="oid" insert="false" update="false"></property>
    		<!-- 第二種加insert=false,update=false -->
    		<!-- <property name="oid" type="java.lang.Integer" column="oid"></property> -->
    		<!-- 多對一 
	    	order:orderItem裡的屬性,也是實體類
	    	oid:實體類的屬性所對應的後臺的欄位
    	    -->
    	 <!-- 會報錯 :解決方法:第一種加,第二種加-->
    	 <!-- 第一種加insert=false,update=false -->
    	<many-to-one name="order" class="com.zking.four.entity.Order" column="oid"></many-to-one>
    	<!-- 第二種加insert=false,update=false -->
    	<!-- <many-to-one name="order" class="com.zking.four.entity.Order" column="oid" insert="false" update="false"></many-to-one> -->
    

級聯查詢 報錯:懶載入 Could not initialize proxy - no session 如果在配置檔案中把它改為 Lazy=true; 查單個時存在問題 改為 Lazy=false; 查所有時存在問題 解決方案:通過欄位控制,強制載入。Hibernate.initialize()

在實體類中定義一個引數
private Integer initOrderItem=0;//0代表懶載入   1代表立即載入

然後去dao方法中判斷它是不是需要強制載入
if(o!=null&&new Integer(1).equals(order.getInitOrderItem())) {
			Hibernate.initialize(o.getOrderItems());  //預設強制載入
		}

普通刪除 先查在刪 先把訂單項刪掉,在刪訂單

`