2

私は休止状態の初心者です。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 プロバイダがありません

次に、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 を使用してそれに関連付けられるクラスがCommentであることを知っています。

4

2 に答える 2