我一直在使用实体管理器merge()方法时遇到问题。
有两个实体'FOO‘和'BAR’,它们本身在模式中没有关系,必须保持这种状态,遗憾的是我不能改变它。FOO中有一个名为PROCESS_CD的列,它与BAR中的CLASS_CD完全相同。CLASS_CD是BAR的主键,但FOO中的PROCESS_CD不是外键。
我想将PROCESS_CD中FOO的值从X更新为Y,但hibernate也尝试更改BAR中的值,因此发生了错误。
我不知道如何指定它应该只在FOO中更新,而不是在BAR中更新
下面是我的数据库模式
Database Schema
我的foo类
@javax.persistence.Entity
@Table(name = "FOO")
public class FooImpl implements Foo {
private Long callCode;
private Journal journal;
@Id
@Column(name = "CALL_CD")
public Long getCallCode() {
return callCode;
}
public void setCallCode(Long aLong) {
callCode = aLong;
}
@ManyToOne(fetch = FetchType.LAZY, targetEntity = BarImpl.class)
@JoinColumn(name = "PROCESS_TYPE")
public Journal getJournal() {
return journal;
}
}我的酒吧课
@javax.persistence.Entity
@Table(name = "BAR")
public class BarImpl implements Bar {
private String Code;
private String Description;
public List<Interaction> interaction;
@Id
@Column(name = "CLASS_CD")
public String getCode() {
return Code;
}
public void setCode(String code) {
Code = code;
}
@Column(name = "CLASS_LONG_DESCR")
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
}这是我的fooDao类
public class FooDao {
public void saveFoo(Foo instance) {
log.debug("update instance");
try {
if (getEntityManager().contains(instance)) {
getEntityManager().merge(instance);
} else {
getEntityManager().persist(instance);
}
log.debug("update successful");
return instance;
} catch (RuntimeException re) {
log.error("update failed", re);
throw re;
}
}
public void startTransaction() throws TransactionException{
EntityTransaction t = getEntityManager().getTransaction();
t.begin();
TransactionManager.setTransaction(t);
}
public void commitTransaction()throws TransactionException {
EntityTransaction t = TransactionManager.retrieveTransaction();
if(t == null)
throw new TransactionException("No transaction associated witht his thread");
t.commit();
}
public void rollbackTransaction() throws TransactionException{
EntityTransaction t = TransactionManager.retrieveTransaction();
if(t == null)
throw new TransactionException("No transaction associated witht his thread");
t.rollback();
}
}最后是我调用来保存的方法
下面是我得到的错误
Caused by: org.hibernate.HibernateException: identifier of an instance of BarImpl was altered from X to Y我希望你能帮忙,因为我在网上找不到任何东西。
谢谢您抽时间见我
发布于 2016-06-02 17:08:23
首先,感谢所有回复我问题的人,你们都非常有用。:D
我发现了我的问题,它存在于我的实际实现中。我没有创建一个新的barImpl,而是去搜索一个,如果它是空的,它需要创建一个新的bar,但如果找到一个,它只会继续并输入新值。
我不知道实体类与数据库中的实际记录保持着一种关系。因此,当我更改DAO找到的实体的值时,当我试图保存foo实体时,它实际上是在尝试更改数据库中的值。
祝您今天愉快
https://stackoverflow.com/questions/37526562
复制相似问题