JPA派生列值根据标识列

编程入门 行业动态 更新时间:2024-10-25 21:31:07
本文介绍了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派生列值根据标识列

本文发布于:2023-05-29 23:04:58,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:标识   JPA

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!