"N + 1选择问题"通常被称为对象关系映射(ORM)讨论中的一个问题,我理解它必须为对象中看起来很简单的事情做出大量的数据库查询.世界.
有没有人对这个问题有更详细的解释?
您使用什么样的替代策略来避免LazyLoadExceptions?
我确实理解在视图中打开会话有以下问题:
但是,如果您知道您的应用程序在单个虚拟机上运行,为什么不通过在视图策略中使用开放会话来减轻您的痛苦?
我没有使用Spring,所以我在一个类中创建一个EntityManager实例.
我使用Hibernate-Eclipse逆向工程来自动生成类.这些类都有一个EntityManager实例.
我不是100%确定Hibernate如何与EntityManager一起工作,所以我想知道这个类(EntityManager)的这么多实例是否可以,例如,交易会出现问题吗?
我是否应该创建一个单独的类来为所有其他类分发EntityManager的静态实例?或者没关系?
编辑:我看到有一些名为@PersistenceContext的东西,它似乎没有将我的persistence.xml作为bean加载到实例变量中,这个功能是否需要spring?(我得到空指针异常,因为它从未被注入)
从我尝试使用@persistencecontext的代码片段
@PersistenceContext(unitName = "manager1")
private EntityManager entityManager;
Run Code Online (Sandbox Code Playgroud)
我的persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="manager1" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="mypassword"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/ptbrowserdb"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
</persistence>
Run Code Online (Sandbox Code Playgroud)