eclipse Hibernate:如何在 Hibernate 中配置 EntityManager?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7470773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 20:32:42  来源:igfitidea点击:

Hibernate: How configure EntityManager in Hibernate?

eclipsehibernatejpapersistencejpa-2.0

提问by Valter Silva

I create a hibernate project with 'hibernate tools'provide by JBoss to Eclipse. Generated the Entities (POJO's) and then the DAO's.

我使用 JBoss 向 Eclipse 提供的“休眠工具”创建了一个休眠项目。生成实体 (POJO),然后生成 DAO。

This way for example:

这种方式例如:

@Entity
@Table(name = "area", catalog = "project_schema", uniqueConstraints = @UniqueConstraint(columnNames = "area"))
public class Area implements java.io.Serializable {

    private Integer id;
    private String area;

    public Area() {
    }

    public Area(String area) {
        this.area = area;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Column(name = "area", unique = true, nullable = false, length = 45)
    public String getArea() {
        return this.area;
    }

    public void setArea(String area) {
        this.area = area;
    }

}

And then the respectely DAO class (generated by Hibernate Tools too):

然后是相应的 DAO 类(也由 Hibernate Tools 生成):

@Stateless
public class AreaHome {

    private static final Log log = LogFactory.getLog(AreaHome.class);

    @PersistenceContext
    private EntityManager entityManager;

    public void persist(Area transientInstance) {
        log.debug("persisting Area instance");
        try {
            entityManager.persist(transientInstance);
            log.debug("persist successful");
        } catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }

    public void remove(Area persistentInstance) {
        log.debug("removing Area instance");
        try {
            entityManager.remove(persistentInstance);
            log.debug("remove successful");
        } catch (RuntimeException re) {
            log.error("remove failed", re);
            throw re;
        }
    }

    public Area merge(Area detachedInstance) {
        log.debug("merging Area instance");
        try {
            Area result = entityManager.merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public Area findById(Integer id) {
        log.debug("getting Area instance with id: " + id);
        try {
            Area instance = entityManager.find(Area.class, id);
            log.debug("get successful");
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
}

But when I try to call AreaHome.persist()it launchs an exception 'NullPointerException'.

但是当我尝试调用AreaHome.persist()它时会启动一个异常'NullPointerException'

I configure my project with hibernate.cfg.xml and everything works fine though:

我使用 hibernate.cfg.xml 配置我的项目,但一切正常:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password"><password></property>
        <property name="hibernate.connection.url">jdbc:mysql://<hostname>:3306/<schema></property>
        <property name="hibernate.connection.username">root</property>
        <!-- <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- SQL -->
        <property name="hibernate.format_sql">true</property>
        <property name="hibernate.show_sql">true</property>
        <!-- C3P0 -->
        <property name="hibernate.c3p0.acquire_increment">2</property>
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.timeout">180</property>
        <property name="hibernate.c3p0.idle_test_period">100</property>
        <!-- Classes -->
        <mapping class="com.suaparte.pojo.Area" />
    </session-factory>
</hibernate-configuration>

This works fine when I try:

当我尝试时,这很好用:

public void persist(Area area) throws ExceptionHandler {
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        session.beginTransaction();
        session.save(area);
        session.getTransaction().commit();
    } catch (HibernateException he) {
        session.getTransaction().rollback();

        throw new ExceptionHandler(he.getCause());
    } finally {
        if (session != null) {
            session.close();
        }
    }

}

But I want to use the DAO's generated by Hibernate Tools because they have EntityManager (which is supposed to be injected, but isn't apparentely).

但是我想使用 Hibernate Tools 生成的 DAO,因为它们有 EntityManager (应该被注入,但不是明显的)。

What I have to do ? Any idea ? Sorry by the long question, but I wanna to be very clear about my problem.

我必须做什么?任何的想法 ?很抱歉这个长问题,但我想非常清楚我的问题。

回答by SVerussa

In fact you need to implement a EntityManagerFactory.

实际上你需要实现一个EntityManagerFactory。

Create a persistence.xml file that resides in the META-INF folder.

创建一个位于 META-INF 文件夹中的 persistence.xml 文件。

Take a look at example

看个例子

http://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html_single/#setup-configuration-packaging

http://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html_single/#setup-configuration-packaging

after the commands to create the EntityManagerFactory and EntityManager then:

在创建 EntityManagerFactory 和 EntityManager 的命令之后:

EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("JavaStackOver");
EntityManager entityManager = entityManagerFactory.createEntityManager();

Resolve dependencies, I used maven:

解决依赖,我用的是maven:

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>4.0.1.Final</version>
</dependency>
<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-entitymanager</artifactId>
  <version>4.0.1.Final</version>
</dependency>
<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-annotations</artifactId>
  <version>3.5.6-Final</version>
</dependency>

Inject on your Dao JPA and Done!

注入您的 Dao JPA 并完成!

The advantage of working with EntityManager is to have the option to change the Hibernate in futuro. Otherwise could use the Session.

使用 EntityManager 的好处是可以选择在未来更改 Hibernate。否则可以使用会话。