Hibernate:如何在Hibernate中配置EntityManager?

时间:2011-09-19 12:15:39

标签: eclipse hibernate jpa persistence jpa-2.0

我使用JBoss向Eclipse提供的'hibernate tools'创建了一个hibernate项目。 生成实体(POJO),然后生成DAO。

这种方式例如:

@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;
    }

}

然后是相应的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;
        }
    }
}

但是当我尝试拨打AreaHome.persist()时,它会启动异常'NullPointerException'

我使用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>

我尝试时效果很好:

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();
        }
    }

}

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

我该怎么办?任何的想法 ? 很抱歉这个问题很长,但我想非常清楚我的问题。

1 个答案:

答案 0 :(得分:3)

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

创建驻留在META-INF文件夹中的persistence.xml文件。

看看例子

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

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

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

解决依赖关系,我使用了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>

注入您的Dao JPA并完成!

使用EntityManager的优点是可以选择在futuro中更改Hibernate。否则可以使用Session。