Hibernate:如何在Hibernate中配置EntityManager? [英] Hibernate: How configure EntityManager in Hibernate?

查看:138
本文介绍了Hibernate:如何在Hibernate中配置EntityManager?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个hibernate项目,'hibernate工具'由JBoss提供给Eclipse。
生成实体(POJO),然后生成DAO。



这样,例如:

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

private Integer id;
私人字符串区域;

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 。区;
}

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

}

然后,尊重DAO类(由Hibernate工具生成):

  @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 success);
} catch(RuntimeException re){
log.error(persist failed,re);
throw re;
}
}

public void remove(Area persistentInstance){
log.debug(remove 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 {
区域结果= entityManager.merge(detachedInstance);
log.debug(merge success);
返回结果;
} catch(RuntimeException re){
log.error(merge failed,re);
throw re;
}
}

public Area findById(Integer id){
log.debug(get Area instance with id:+ id);
try {
区域实例= 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.0encoding =UTF-8?> 
<!DOCTYPE hibernate-configuration PUBLIC
- // Hibernate / Hibernate配置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>
<! - 类 - >
< mapping class =com.suaparte.pojo.Area/>
< / session-factory>
< / hibernate-configuration>

当我尝试:



< p $ p> public void persist(Area area)throws ExceptionHandler {
Session session = HibernateUtil.getSessionFactory()。openSession();
try {
session.beginTransaction();
session.save(area);
session.getTransaction()。commit();
} catch(HibernateException他){
session.getTransaction()。rollback();

抛出新的ExceptionHandler(he.getCause());
} finally {
if(session!= null){
session.close();
}
}

}

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



我要做什么?任何想法 ?
对不起,长期的问题,但我想非常清楚我的问题。

解决方案

其实你需要实现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:

 <依赖性> 
< groupId> org.hibernate< / groupId>
< artifactId> hibernate-core< / artifactId>
< version> 4.0.1.Final< / version>
< / dependency>
<依赖关系>
< groupId> org.hibernate< / groupId>
< artifactId> hibernate-entitymanager< / artifactId>
< version> 4.0.1.Final< / version>
< / dependency>
<依赖关系>
< groupId> org.hibernate< / groupId>
< artifactId> hibernate-annotations< / artifactId>
< version> 3.5.6-Final< / version>
< / dependency>

注入您的Dao JPA和完成!



与EntityManager一起使用的优点是可以更改futuro中的Hibernate。否则可以使用会话。


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

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):

@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'.

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

<?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).

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

解决方案

In fact you need to implement a EntityManagerFactory.

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

Take a look at example

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 entityManagerFactory = Persistence.createEntityManagerFactory("JavaStackOver");
EntityManager entityManager = entityManagerFactory.createEntityManager();

Resolve dependencies, I used 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!

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

这篇关于Hibernate:如何在Hibernate中配置EntityManager?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆