データベースへの書き込みに通常より時間がかかるという問題が発生していました。これらの遅延書き込みにより、書き込み後に実行される論理ブロックが正しくなくなります。サーバーを再起動すると、すべてが正常に機能します。私の懸念は、サーバーが遅れ始めると、この遅延書き込みの問題が再び発生することです。
EntityManager で Java Transaction API (JTA) を使用しています。
@Inject
private EntityManager em;
必要なときに EntityManager に明示的なコミットを強制するにはどうすればよいですか?
次のコード行を実行する前に、書き込みが完了するまで待つにはどうすればよいですか?
EntityManager は自動コミットしますか? もしそうなら、いつそれをしますか?
em.getTransaction().commit(); を試しました。エラーが発生します: JTA can not use getTransaction
私はいくつかの調査を行い、em.getTransaction().begin(); を使用することになっていないことがわかりました。em.getTransaction().commit(); も、これらの命令は RESOURCE_LOCAL トランザクション タイプで使用されます。私の場合、トランザクションはコンテナーによって管理されます。
コードスニペット:
public void addNewUserRoleWithMonthExpiry(User user,String role,Date startDate,Date newDate){
Set<Userrole> roles = user.getUserroles();
Role r = roleRepostitory.findByName(role);
Userrole ur = new Userrole(user, r, startDate, newDate);
roles.add(ur);
em.persist(ur); //<==== I want to make sure this committed now!!!
}
もし em.persist(ur); Userrole をデータベースにすぐにコミットせず、その後実行されるコードはデータベースから読み取り、その Userroel が存在するかどうかを確認しますが、そのロールはまだ書き込まれていないため、正しくありません。
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_2_0.xsd"
version="2.0">
<persistence-unit name="persistence-memberDB">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<!-- <jta-data-source>java:/DefaultDS</jta-data-source> -->
<jta-data-source>java:/mydb</jta-data-source> <!-- See <datasource jndi-name="..."> . -->
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.cache.use_second_level_cache" value="false"/>
<property name="hibernate.cache.use_query_cache" value="false" />
<property name="hibernate.cache.use_minimal_puts" value="true"/>
<property name="hibernate.connection.zeroDateTimeBehavior" value="convertToNull"/>
<property name="hibernate.c3p0.acquire_increment" value="1"/>
<property name="hibernate.c3p0.min_size" value="5"/>
<property name="hibernate.c3p0.max_size" value="20"/>
<property name="hibernate.c3p0.timeout" value="60"/>
<property name="hibernate.3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.idle_test_period" value="3000"/>
<property name="transaction.factory_class" value="org.hibernate.transaction.JDBCTransactionFactory"/>
<property name="current_session_context_class" value="thread"/>
<property name="hibernate.search.autoregister_listeners" value="false"/>
</properties>
</persistence-unit>
</persistence>