hibernate删除二级jpa2.0

hibernate delete second level jpa2.0

我需要在我的应用程序中删除可缓存的所有数据 table。 我想删除所有内容,我必须删除二级缓存,然后使用截断。

@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

我找到了解决方案, 我试图在删除数据之前清理缓存的问题,这不是最佳做法

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 执行 SQL 语句以同步 JDBC 连接的状态与会话级缓存中保存的对象的状态。所以我很高兴能够在没有 ID 问题的情况下保存其他实体