Hibernate4的檢索策略分爲:類級別檢索和關聯級別檢索兩大類。java
類級別檢索分爲當即檢索、延遲檢索。對於Session的檢索方式,類級別檢索策略僅適用於load方法。是經過<class>中的 'lazy'屬性來肯定的,而類級別的lazy屬性默認是true。session
<!-- lazy 的默認屬性 true --> <class name="com.study.hibernate.domain.Customer" table="t_customer" catalog="db_hibernate" lazy="false">
@Test public void queryTest(){ Configuration configuration = new Configuration().configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); Session session = sessionFactory.openSession(); Transaction tracsaction = session.beginTransaction(); //lazy=true時 //Customer customer = (Customer) session.get(Customer.class, new Long(1)); //結果 //Hibernate: /* load com.study.hibernate.domain.Customer */ select customer0_.id as id1_0_0_, customer0_.name as name2_0_0_ from db_hibernate.t_customer customer0_ where customer0_.id=? Customer customer1 = (Customer) session.load(Customer.class, new Long(1)); //結果 //沒有執行查詢語句 //當觸發了customer1對象裏的get()方法時才執行了查詢 //customer1.getName(); //Hibernate: /* load com.study.hibernate.domain.Customer */ select customer0_.id as id1_0_0_, customer0_.name as name2_0_0_ from db_hibernate.t_customer customer0_ where customer0_.id=? tracsaction.commit(); session.close(); sessionFactory.close(); }
關聯級別檢索分爲:當即檢索、延遲檢索、迫切左外鏈接檢索。app
get()方法和query查詢方式都爲當即檢索。dom
<set name="orders" cascade="all" lazy="false"> <!-- lazy默認爲 true -->
Customer customer1 = (Customer) session.load(Customer.class, new Long(1)); customer1.getName(); //結果 Hibernate: /* load com.study.hibernate.domain.Customer */ select customer0_.id as id1_0_0_, customer0_.name as name2_0_0_ from db_hibernate.t_customer customer0_ where customer0_.id=? Hibernate: /* load one-to-many com.study.hibernate.domain.Customer.orders */ select orders0_.customer_id as customer3_0_1_, orders0_.id as id1_1_1_, orders0_.id as id1_1_0_, orders0_.name as name2_1_0_, orders0_.customer_id as customer3_1_0_ from db_hibernate.t_orders orders0_ where orders0_.customer_id=?
當lazy=false時customer對象被加載的同時,orders對象也被加載fetch
<set name="orders" cascade="all" fetch="join">
Customer customer1 = (Customer) session.load(Customer.class, new Long(1)); System.out.println(customer1); //結果 Hibernate: /* load com.study.hibernate.domain.Customer */ select customer0_.id as id1_0_1_, customer0_.name as name2_0_1_, orders1_.customer_id as customer3_0_3_, orders1_.id as id1_1_3_,orders1_.id as id1_1_0_, orders1_.name as name2_1_0_, orders1_.customer_id as customer3_1_0_ from db_hibernate.t_customer customer0_ left outer join db_hibernate.t_orders orders1_ on customer0_.id=orders1_.customer_id where customer0_.id=? Customer [id=1, name=zhangsan, orders=[Orders [id=2, name=apple], Orders [id=1, name=orange]]]
當fetch="join" 時 爲當即檢索其SQL語句爲左外鏈接,忽略lazy="true"。ui