简体   繁体   English

JPA自动递增合并

[英]JPA merge on auto increment

I have an Entity that has the following multiple fields along with a field that is autogenerated on an insert 我有一个实体,该实体具有以下多个字段以及在插入时自动生成的字段

Now everytime I want to do an update using merge() in my DAO, it will add a new entry instead of updating the current entry. 现在,每次我想在我的DAO中使用merge()进行更新时,它将添加一个新条目而不是更新当前条目。 I am assuming this is due to UPDATE statement on id and the id is new everytime. 我假设这是由于id上的UPDATE语句引起的,并且id每次都是新的。 Is there a way within JPA (Hibernate) to avoid writing a new record in the database and just to an update instead. JPA(Hibernate)中是否有一种方法可以避免在数据库中写入新记录,而只是更新。 Please find below my entity object: 请在我的实体对象下面找到:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "CONFIG_ID")
private long configID;

@ManyToOne
@JoinColumns({
        @JoinColumn(name = "CID", referencedColumnName = "CID", insertable = true, updatable = false),
        @JoinColumn(name = "DID", referencedColumnName = "DID", insertable = true, updatable = false)})
@Version private <Object> dE;
@Column(name = "HISTORY", nullable = false, unique = false)
private String history;

merge() is supposed for detached entity use . merge()应该用于独立实体。 It is an update or insert action depending if the identity of the merged object is null or not. 这是一个更新或插入操作,具体取决于合并对象的标识是否为null。 If it is null , a new record will be inserted. 如果为null,将插入一条新记录。

To correctly update an entity in JPA , you simply load it and change its properties. 要在JPA中正确更新实体,您只需加载它并更改其属性。 When the transaction commit , JPA will figure out if there are any properties changes and issue the UPDATE SQL if there are changes. 当事务提交时,JPA将确定是否有任何属性更改,如果有更改,则发出UPDATE SQL。 No need to call any methods on EntityManager for any update. 无需调用EntityManager上的任何方法进行任何更新。

Reference: 参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM