FetchType的区别是什么。LAZY和FetchType。Java持久性API中的EAGER ?
当前回答
public enum FetchType extends java.lang.Enum Defines strategies for fetching data from the database. The EAGER strategy is a requirement on the persistence provider runtime that data must be eagerly fetched. The LAZY strategy is a hint to the persistence provider runtime that data should be fetched lazily when it is first accessed. The implementation is permitted to eagerly fetch data for which the LAZY strategy hint has been specified. Example: @Basic(fetch=LAZY) protected String getName() { return name; }
源
其他回答
如果你在使用Hibernate,你可以在调用getStudents()方法时调用Hibernate.initialize():
Public class UniversityDaoImpl extends GenericDaoHibernate<University, Integer> implements UniversityDao {
//...
@Override
public University get(final Integer id) {
Query query = getQuery("from University u where idUniversity=:id").setParameter("id", id).setMaxResults(1).setFetchSize(1);
University university = (University) query.uniqueResult();
***Hibernate.initialize(university.getStudents());***
return university;
}
//...
}
I may consider performance and memory utilization. One big difference is that EAGER fetch strategy allows to use fetched data object without session. Why? All data is fetched when eager marked data in the object when session is connected. However, in case of lazy loading strategy, lazy loading marked object does not retrieve data if session is disconnected (after session.close() statement). All that can be made by hibernate proxy. Eager strategy lets data to be still available after closing session.
LAZY:它惰性地获取子实体,即在获取父实体时,它只是获取子实体的代理(由cglib或任何其他实用程序创建),当你访问子实体的任何属性时,它实际上是由hibernate获取的。
EAGER:它与父实体一起获取子实体。
为了更好地理解,请参阅Jboss文档,或者使用hibernate。Show_sql =true,检查hibernate发出的查询。
对集合的EAGER加载意味着在获取它们的父类时,它们被完全获取。如果你有课程并且它有List<Student>,所有的学生在课程被获取的同时从数据库中获取。
另一方面,LAZY意味着只有当您试图访问List的内容时才会获取它们。例如,调用course.getStudents().iterator()。调用List上的任何访问方法都将启动对数据库的调用以检索元素。这是通过围绕列表(或集合)创建代理来实现的。所以对于惰性集合,具体的类型不是ArrayList和HashSet,而是PersistentSet和PersistentList(或PersistentBag)。
基本上,
LAZY = fetch when needed
EAGER = fetch immediately
推荐文章
- JavaFX应用程序图标
- Java:强/软/弱/幻影引用的区别
- 在序列化和反序列化期间JSON属性的不同名称
- 获取Android设备名称
- Gradle代理配置
- 如何获得具有已知资源名称的资源id ?
- 在Android上将字符串转换为整数
- 为什么“System.out。”println“工作在Android?
- 在Java中什么时候使用可变参数?
- Mockito的argumentCaptor的例子
- 我如何告诉Spring Boot哪个主类用于可执行jar?
- 如何将Java8流的元素添加到现有的列表中
- 在Java 8中是否可以转换流?
- 不区分大小写的字符串作为HashMap键
- 什么是maven中的“pom”打包?