Kundera cassandra - 事务回滚和实体更新

时间:2016-01-26 11:54:55

标签: java cassandra kundera

我使用Kundera-Cassandra 3.2并希望使用昆德拉的交易管理。

我的处理方式如下:

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);中出现错误时,管理器回滚事务,但不执行更新语句,他为merge方法创建了一个delete语句。原因是,在调用合并方法时,kundera会创建一个insert语句而不是更新。但是如何说昆德拉做出更新以回滚交易还有更新。

日志:

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;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

根据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中都是相似的。