我使用Kundera-Cassandra 3.2,并希望使用Kundera的事务管理。

我的处理如下所示:

EntityManager manager = repo.getEntityManagerFactory().createEntityManager(CassandraRepository.getProperties());

try{
    manager.getTransaction().begin();

    this.repo.update(account1, manager); //calls the merge method of the Entitymanager
    this.repo.save(account2, manager); //calls the persist method of the Entitymanager

    manager.getTransaction().commit();

} catch(Exception e){
    if(manager.getTransaction().isActive()){
        manager.getTransaction().rollback();
    }
} finally {
    manager.clear();
    manager.close();
}


this.repo.save(account2, manager);中发生错误时,管理器将回滚事务,但不执行update语句,而是为merge方法创建delete语句。原因是,在调用merge方法时,kundera创建一个insert语句而不是一个更新。但是怎么说Kundera进行更新以使事务回滚也具有更新。

日志:

12:42:41.185 [http-bio-8080-exec-3] INFO com.impetus.client.cassandra.CassandraClientBase - Returning delete query DELETE FROM "account" WHERE "id" = 'MCSP-000000000004'.
12:42:41.211 [http-bio-8080-exec-3] INFO com.impetus.client.cassandra.CassandraClientBase - Returning delete query DELETE FROM "account" WHERE "id" = 'MCSP-000000000005'.


编辑(我的存储库):

public class CassandraRepository<T> {

    @PersistenceUnit
    private EntityManagerFactory entityManagerFactory;

    public static Map<String, String> getProperties() {
        final Map<String, String> properties = new HashMap<String, String>();
        properties.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);
        return properties;
    }



    public void update(T entity, EntityManager manager) throws Exception{
        try {
            manager.merge(entity);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    public void save(T entity, EntityManager manager) throws Exception{
        try {
            manager.persist(entity);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}

最佳答案

根据JPA的说法,要更新实体,您必须首先将其置于托管状态(通过获取)

例:-

        PersonCassandra p = entityManager.find(PersonCassandra.class, "2");

        entityManager.getTransaction().begin();
        p.setMonth(Month.JAN);
        entityManager.merge(p);
        entityManager.persist(p3);
        entityManager.getTransaction().commit();


INSERT和UPDATE语句不存在问题,因为对于Cassandra而言,两者都非常相似。

09-30 18:38