3

我正在尝试在 glass fish 服务器上使用 hibernate 和 JPA 2.0 创建一个新的 Java EE 项目。你们能否为我提供一些资源来配置上述内容,以便它们无缝工作?我曾尝试使用 netbeans 并使用休眠提供程序生成持久性单元,但最终出现此错误:

javax.persistence.PersistenceException: [PersistenceUnit: DBAppPU] Unable to build EntityManagerFactory
4

2 回答 2

6

首先,通过更新工具安装 Hibernate 支持(或按照手动过程)。其次,提供一个 JPA 2.0persistence.xml来使用 Hibernate 作为 JPA 提供者:

<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="MyPu" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <!-- JNDI name of the database resource to use -->
    <jta-data-source>jdbc/__default</jta-data-source>
    <properties>
      <!-- The database dialect to use -->
      <property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect" />
      <!-- update database tables at deployment -->
      <property name="hibernate.hbm2ddl.auto" value="update"/>
      <!-- log the generated SQL -->
      <property name="hibernate.show_sql" value="true"/>
    </properties>
  </persistence-unit>
</persistence>

资源

于 2010-08-31T16:58:54.200 回答
0

本指南用于在 NetBeans.8.0 IDE 中集成 hibernate.4.3.5 和 EJB 和 GlassFish.4.0。在net beans中创建一个web项目,并在项目中添加hibernate jar文件,其他配置MySql和glassfish相关的设置非常简单,本文不再赘述,然后创建persistence.xml文件如下:

<persistence-unit name="omidashouriPU" transaction-type="Resource_Local">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
            <property name="hibernate.archive.autodetection" value="class"/>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/YourSchemaName"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value="yourpassword"/>
            <property name="hibernate.show_sql" value="true"/>
    </properties>
</persistence-unit>

在用于创建 EntityManager 的 EJB 类(使用 @Stateless 注释的类)中,使用以下语法:

EntityManagerFactory emf = Persistence.createEntityManagerFactory("omidashouriPU");
EntityManager em = emf.createEntityManager();
em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(YourEntityObject);
em.getTransaction().end();

As you Know when you are using “transaction-type="Resource_Local", you have to manage the transaction by yourself, mean that, managing of opening and closing the transaction is our responsibility.
于 2014-07-13T09:12:32.517 回答