我需要在我的应用程序中删除可缓存表中的所有数据。 我认为要删除所有内容,我必须删除二级缓存,然后使用截断。
@Entity
@Table(name = "\"cpf_formacode\"")
@Cacheable
public class CpfRefFormaCode implements Serializable {
.......
}
道方法:
public void deleteAll() {
SessionFactory sf = em.unwrap(SessionFactory.class);
sf.getCache().evictEntityRegion(CpfRefFormaCode.class);
em.createNativeQuery("TRUNCATE TABLE cpf_formacode").executeUpdate();
}
持久性文件:
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="org.hibernate.FlushMode" value="commit" />
<!-- property name="hibernate.hbm2ddl.auto" value="create-drop" / -->
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.cache.use_second_level_cache" value="true" />
<property name="hibernate.cache.use_query_cache" value="true" />
<property name="hibernate.cache.infinispan.cachemanager" value="java:jboss/infinispan/hibernate" />
<property name="hibernate.cache.region.factory_class" value="org.jboss.as.jpa.hibernate4.infinispan.InfinispanRegionFactory" />
<property name="hibernate.cache.infinispan.statistics" value="true" />
</properties>
我有错误:
17:50:17,161 ERROR [org.jboss.as.ejb3.tx.CMTTxInterceptor] (http--127.0.0.1-8080-2) javax.ejb.EJBTransactionRolledbackException: Hibernate cannot unwrap interface org.hibernate.SessionFactory
17:50:17,163 ERROR [org.jboss.ejb3.invocation] (http--127.0.0.1-8080-2) JBAS014134: EJB Invocation failed on component CpfRefFormaCodeDao for method public void com.agefos.corp.business.dao.CpfRefFormaCodeDao.deleteAll(): javax.ejb.EJBTransactionRolledbackException: Hibernate cannot unwrap interface org.hibernate.SessionFactory
Caused by: javax.persistence.PersistenceException: Hibernate cannot unwrap interface org.hibernate.SessionFactory
答案 0 :(得分:0)
我完成了findig解决方案, 我在删除数据之前试图清理缓存的问题,这不是最佳实践
public void deleteAll() {
try {
TypedQuery<MyEntity> query = em.createQuery("From MyEntity f", MyEntity.class);
query.setHint("org.hibernate.cacheable", true);
List<MyEntity> result = null;
result = query.getResultList();
if (!result.isEmpty()) {
for (MyEntity f : result) {
em.remove(f);
}
}
em.flush();
} catch (Exception e) {
throw new PersistanceException("An error occurred while attempting to delete an instance of an object : " + entityClass, e);
}
}
通过添加
解决了问题 em.flush();
换句话说,flush告诉Hibernate执行将JDBC连接状态与会话级缓存中保存的对象状态同步所需的SQL语句。所以我在没有ID问题的情况下保存其他实体