jpa抓取策略详解fetch(lazy ,eager)
2009-09-26 00:00:00 来源:WEB开发网junit的测试方法
Java代码
@Test public void query() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa-hibernate");
EntityManager em = factory.createEntityManager();
Garage garage = em.find(Garage.class, 1);
em.close();
factory.close();
}
调用query方法的时候发出的sql语句是:
Sql代码
Hibernate: select garage0_.gid as gid1_0_, garage0_.garagenum as garagenum1_0_ from Garage garage0_ where garage0_.gid=?
也就是仅仅获取了garage对象,而没有获取与garage关联的auto对象
-----------------
(二)在Garage.java中添加fetch=FetchType.EAGER字段
@OneToMany(cascade={CascadeType.PERSIST},fetch=FetchType.EAGER,mappedBy="garage")
public Set<Auto> getAutos() {
return autos;
}
再次运行query方法,这一次发出的sql语句是:
Sql代码
Hibernate: select garage0_.gid as gid1_1_, garage0_.garagenum as garagenum1_1_, autos1_.garageid as garageid3_, autos1_.autoId as autoId3_, autos1_.autoId as autoId0_0_, autos1_.autonum as autonum0_0_, autos1_.autotype as autotype0_0_, autos1_.garageid as garageid0_0_ from Garage garage0_ left outer join Auto autos1_ on garage0_.gid=autos1_.garageid where garage0_.gid=?
这一次由于将jpa默认的抓取策略改为fetch=FetchType.EAGER
所以jpa在加载数据的时候一次性的加载了和garage相关联的数据
说明:由于fetch=FetchType.EAGER加载数据的时候是一次性加载可能会造成不必要的性能浪费,使用是应该慎重考虑
更多精彩
赞助商链接