JPA派生列值根据标识列 [英] JPA Derived Column value based on Identity column

查看:93
本文介绍了JPA派生列值根据标识列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JPA 2.0(Hibernate 4.2.4.Final / Spring 3.2.8.Release)/ Mysql 5.6



对于管理实体E w /自动生成的主键例如

  ... 
@Id
@GeneratedValue
private int id;

@Column
private String foo;

@版本
@Column(name =mod_date)
私人Timetamp modDate;
...

foo需要等于:{id}:出于传统原因。例如。如果id是204,那么foo将会是:204:
为了在交易中发生这种情况,这是行得通的

  em.persist(E); 
em.detach(e);
e = em.find(e.getId());
e.setFoo(:+ e.getId()+:);
...

有没有更好的计算派生列的方法,在生成的ID?
如果没有上述hack,即在persist结果为org.hibernate.StaleObjectException后直接更新列。我发现这发生在单元测试中(事实上,我可以单步测试代码,并且可以重排异常,这排除了通常与StaleObjectException关联的多线程问题。

解决方案

您可以使用JPA PostPersist事件监听器来处理这个问题。

  @Id 
@GeneratedValue
private int id;

@Column
private String foo;
$ b @PostPersist $ b $ public void onSave(){
foo =:+ id +:;
}

根据JPA 2规范:


PostPersist和PostRemove回调方法在实体被持久化后调用
实体这些
回调函数也会在这些
操作所级联的所有实体上调用PostPersist和PostRemove方法将在数据库插入和删除操作
之后调用
这些数据库操作可能会在
persist,merge或remove操作被调用之后直接发生,或者它们可能在发生刷新操作后直接发生(可能在事务结束时
) 。 在PostPersist方法中生成的主键值为


JPA 2.0 (Hibernate 4.2.4.Final/Spring 3.2.8.Release) / Mysql 5.6

For a managed entity E w/ auto-generated primary key e.g.

...
@Id
@GeneratedValue
private int id;

@Column
private String foo;

@Version
@Column(name="mod_date")
private Timetamp modDate;
...

foo needs to equal :{id}: for legacy reasons. E.g. if id was 204, foo would be ":204:" For this to happen w/in a transaction this is what works

em.persist(e);
em.detach(e);
e = em.find(e.getId());
e.setFoo(":" + e.getId() + ":");
...

Is there a better way of computing a derived column where the value depends on the generated Id ? Without the above hack i.e. directly updating the column after persist results in a org.hibernate.StaleObjectException. I see this happening in unit tests (in fact I can step through the unit test code and can repro the exception which rules out the multi thread issue usually associated w/ StaleObjectException

解决方案

You can use a JPA PostPersist Event Listener to handle this.

@Id
@GeneratedValue
private int id;

@Column
private String foo;

@PostPersist
public void onSave(){
    foo = ":" + id + ":";
}

From the JPA 2 specification:

The PostPersist and PostRemove callback methods are invoked for an entity after the entity has been made persistent or removed. These callbacks will also be invoked on all entities to which these operations are cascaded. The PostPersist and PostRemove methods will be invoked after the database insert and delete operations respectively. These database operations may occur directly after the persist, merge, or remove operations have been invoked or they may occur directly after a flush operation has occurred (which may be at the end of the transaction). Generated primary key values are available in the PostPersist method.

这篇关于JPA派生列值根据标识列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆