[英]set the id of auto increment field in hibernate is not saved properly
帐户类别:
@Entity
@Table(name = "Account")
public class Account {
...
private String accountId;
...
@Id
@GeneratedValue
@Column(name = "accountId")
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
...
如果我尝试这样做:
temp = new Account();
temp.setAccountId(tempId); //
session.save(temp);
System.out.println("accountid...." + temp.getAccountId());
它打印一个不等于tempId的accountId,我认为它是因为它是表中的一个自动增量字段
另一方面,如果我这样做:
temp = new Account();
session.save(temp);
temp.setAccountId(tempId);
session.merge(temp);
我得到例外:
org.hibernate.HibernateException: identifier of an instance
of ... was altered from 1244 to 1221
如何覆盖ID?
您无需设置ID,当您保留实体时,hibernate会自动分配ID(根据使用生成的值注释定义的策略)。
不确定,但是您使用的是String值,该如何递增? 您不想使用Long吗?
首先,您不得将值分配给生成的字段。 它将替换为生成的一个。 它是预期的行为。
其次,您不得更改ID。 所有实体均通过其ID映射到数据库。 如果您更改ID,则其为新实体。 您无法更新它,必须将其保存。
我不认为任何JPA实施都具有压倒性的id机制。 如果您想自己设置id即可,请删除GeneratedValue批注,并对持久性存储执行相同的操作。 然后,您可以将值另存为ID。
如果要使用特定的ID,并且数据库中已经存在具有该ID的实体,则必须首先从会话中获取该实体:
Account a = session.get(Account.class, id);
然后进行更改并合并。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.