我有兩個實體,Type
和TypeValue
。每個Type
可以有幾個TypeValue
。在試圖保留新的TypeValue
時,出現數據庫錯誤Type
已存在(這是正確的,但我不想再添加它,我只想添加一個新的'TypeValue')。我有類似的類沒有IdClass
正在工作,所以我假設@IdClass定義是錯誤的或我忘了定義的東西,以便所引用的對象不更新。如何防止在使用@IdClass時保存被引用實體?
如何防止被推薦實體Type
在使用@IdClass
時TypeValue
的保存?
類定義:
@Entity
@Table(name = "TYPE", schema = "VOC")
public class Type implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "TYPEID")
private String typeID;
@Column(name = "NAME")
private String name;
@OneToMany(mappedBy = "type")
private List<TypeValue> listTypeValue;
// constructor, getter, setter, equals, hashcode, ...
}
@Entity
@IdClass(TypeValueID.class)
@Table(name = "TYPE_VALUE", schema = "VOC")
public class TypeValue implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@ManyToOne
@JoinColumn(name = "TYPEID")
@ForeignKey(name = "TYPEVALUE_FK")
private Type type;
@Id
@Column(name = "VALUE")
private String value;
// constructor, getter, setter, equals, hashcode, ...
}
public class TypeValueID implements Serializable {
private static final long serialVersionUID = 1L;
String type;
String value;
// equals, hashcode
}
使用示例:
Type type = ... // get existing type with typeID "DETAIL"
Session session = sessionFactory.getCurrentSession();
TypeValue newTypeValue = new TypeValue(type, "new value");
session.save(newTypeValue);
session.flush();
拋出的異常:
SEVERE: Servlet.service() for servlet [spring] in context with path [/project] threw exception [Request processing failed; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "type_pkey"
Detail: Key (typeid)=(DETAIL) already exists.
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2455)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2155)
...
我(當前)不允許使用代理鍵,所以我被自然鍵卡住了,在這種情況下,它是一個字符串。但否則這將是一個解決方案。 – Zwie