Hibernate區分不同對象的方法
1.關系數據庫按主鍵區分不同記錄。
- create table CUSTOMERS (ID int promary key not null, NAME varchar(15));
- insert into CUSTOMERS values(1, 'Tom');
- insert into CUSTOMERS values(3, 'Tom');
2.Java語言按內存地址區別不同的對象。
- Customer c1 = new Customer("Tom");
- Customer c2 = new Customer("Tome");
- Customer c3 = c1;
- // c1 == c3 結果為true
- // c1 == c2 結果為false
3.Hibernate用對象標識符(OID)來區分不同對象。
- Customer c1 = (Customer)session.load(Customer.class, new Long(1));
- Customer c2 = (Customer)session.load(Customer.class, new Long(1));
- Customer c3 = (Customer)session.load(Customer.class, new Long(3));
- // c1 == c2 結果為true
- // c1 == c3 結果為false
以上程序中,三次調用了Session的load()方法,分別加載OID為1或3的Customer對象。以下是Hibernate三次加載Customer對象的流程。
(1)第一次加載OID為1的Customer對象時,先從數據庫的CUSTOMERS表中查詢ID為1的記錄,再創建相應的Customer實例,把它保存在Session緩存中,最后把這個對象的引用賦值給變量c1。
(2)第二次加載OID為1的Customer對象時,直接把緩存中OID為1的Customer對象的引用賦值給c2,因為c1和c2引用同一個Customer對象。
(3)當加載OID為3的Customer對象時,由于在緩存中不存在這樣的對象,所以必須再次到數據庫中查詢OID為3的記錄,再創建相應的Customer實例,把它保存存在Session緩存中,最后把這個對象的引用賦值給變量c3。
【編輯推薦】
- Hibernate創建命名策略
- Hibernate的unsaved-value
- Hibernate中get和load方法的區別
- 項目添加Hibernate支持
- Hibernate查詢語言HQL 八大要點