【问题标题】:Can't access EntityManager with JPA 2.1 and Hibernate5无法使用 JPA 2.1 和 Hibernate5 访问 EntityManager
【发布时间】:2016-12-06 18:47:26
【问题描述】:

我有一个使用 Hibernate 5 的应用程序,并添加了 JPA 2.1 以使用 CriteriaBuilder.createCriteriaUpdate() 执行批量更新。

但是我需要从 EntityManager.getCriteriaBuilder() 中分配 CriteriaBuilder,我无法获取 EntityManager。

我没有 persistence.xml 文件,我认为 Hibernate 会为我提供一个 EntityManager。

我在 DAO 类中尝试了以下注解:

@Autowired
EntityManager entityManager

@PersistenceContext
EntityManager entityManager;

两者都无法注入依赖项。 我也尝试实例化一个 EntityManagerFactory,但它失败了,因为我没有 persistence.xml 文件。所有实体都这样注释:

@Entity
@Table(name = "My_Entity")
public class MyEntity extends BaseEntity {

private static final long serialVersionUID = -8442071276091708080L;

 @Column(name = "VALUE", nullable = false)
 private BigDecimal value;

...
}

这是我的 pom.xml 的一部分:

<dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.1.3.Final</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.1.3.Final</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.1-api</artifactId>
        <version>1.0.0.Final</version>
    </dependency>

applicationContext.xml

<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

<bean id="transactionManager"
      class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
    <property name="nestedTransactionAllowed" value="true"/>
</bean>

Hibernate 实例化 SessionFactory,有没有办法从中获取 EM?

【问题讨论】:

    标签: java spring hibernate jpa hibernate-entitymanager


    【解决方案1】:

    如果您使用 spring,那么使用 spring boot 启动器模块会容易得多。对于 JPA,它将是“spring-boot-starter-data-jpa”,您可以找到 maven 依赖项 here 的定义。

    此外,您能否添加有关您的配置的更多信息?你说你不使用persistence.xml 那么你用什么来设置你的数据源?

    【讨论】:

    • 问题已更新。我确实使用 Spring,但不是 Spring Boot,也许我可以添加你提到的那个包?我只使用注释来映射数据。
    • 你是否也在某处定义了bean sessionFactory?数据源声明呢?您的应用在使用 JPA 之前是否正常工作?
    • 哎呀之前不是要提交该消息,它没有完成。
    • grmbl no edit >baeldung.com/the-persistence-layer-with-spring-and-jpa 以了解如何操作。
    猜你喜欢
    • 2012-09-08
    • 2014-06-28
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 2017-02-25
    • 2013-07-25
    • 1970-01-01
    相关资源
    最近更新 更多