persistence.xml在Java客户端应用程序中的位置

时间:2013-08-14 15:00:20

标签: java hibernate persistence.xml

我是Hibernate的新手。为了通过EntityManager获取事务,我需要使用EntityManager Factory。当我把这个代码块放在我的文件上时:

EntityManagerFactory entityManagerFactory = Persistence
            .createEntityManagerFactory("Comment");

EntityManager entityManager = entityManagerFactory.createEntityManager();

EntityTransaction transaction = entityManager.getTransaction();

transaction.begin();
entityManager.persist(obj);
transaction.commit();

我有这个例外:

javax.persistence.PersistenceException:没有名为Comment的EntityManager的持久性提供程序

然后我意识到我需要添加一个persistence.xml文件:

<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_1_0.xsd" version="1.0">
  <persistence-unit name="QuestionsComments" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>Comment</class>
    <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect"/>
      <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
      <property name="hibernate.show_sql" value="true"/>
      <property name="hibernate.connection.username" value="root"/>
      <property name="hibernate.connection.password" value="root"/>
      <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/sogdb"/>
      <property name="hibernate.max_fetch_depth" value="3"/>
    </properties>
  </persistence-unit>
</persistence>

实际上,我使用的应用程序不是Java on Server应用程序(我有一个客户端应用程序)。这意味着没有包含persistence.xml文件的META-INF文件夹。

我的问题是:

1-我需要把persistence.xml文件放在哪里?

2-下面的代码是否正常?知道我的数据库中的表是 QuestionsComments ,而我的使用Hibernate与之相关的类是评论

2 个答案:

答案 0 :(得分:2)

如果您正在使用Eclipse,那么将JPA facet添加到项目中可以让Eclipse负责为您设置这些内容。它将创建META-INF文件夹,并可在其中生成存根persistence.xml文件。您不必在服务器上运行代码就可以在jar文件中包含META-INF文件夹。

创建EntityManagerFactory时,字符串参数应该是持久性单元的名称。我建议在实体类中使用注释来指定表名,id列等。

编辑:固定链接。

答案 1 :(得分:0)

  1. Hibernate JPA Quick Start Guide的这一部分清楚回答。它进入META-INF

  2. 查看刚刚关联的相同指南。

  3. 就个人而言,我更喜欢特定于Hibernate的配置hibernate.cfg.xml,带有注释用于映射,而Hibernate用SessionFactory用于事务访问;我发现更容易理解 - 虽然这可能是因为我最初学会了如何使用Hibernate而不知道如何使用JPA。