gpt4 book ai didi

java - 如果 ID 已存在,则将实体与另一个实体一起保存为属性时出错

转载 作者:行者123 更新时间:2023-12-01 10:46:48 25 4
gpt4 key购买 nike

我有两个实体。

@Entity
@Table(name = "OPERATORS_REPORT_TABLE")
@NamedQuery(name = "OperatorsReportTable.getAll", query = "SELECT c from OperatorsReportTable c")
public class OperatorsReportTable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "OPERATOR_FIO", length = 2000)
private String operator_fio;
@Column(name = "NICKNAME", length = 500)
private String nickname;
@Column(name = "OPERATOR_AVAYA_ID", length = 4)
private int operator_avaya_id;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "LANGUAGES_LIST_ID")
private LanguagesList languagesList;

@Entity
@Table(name = "LANGUAGES_LIST")
@NamedQuery(name = "LanguagesList.getAll", query = "SELECT c from LanguagesList c")
public class LanguagesList {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "LANGUAGE_NAME", length = 2000)
private String languageName;

我填写DB的LanguagesList。我从 Web 表单创建了 OperatorsReportTable。例如我有表

id language
0 eng
1 ru

我在数据库中手动填写。

我有第二张 table

id operator_fio nickname operator_avaya_id LANGUAGES_LIST_ID
0 name 1 nickname1 1111 1
1 name 2 nickname2 2222 2

如果我也在数据库中手动创建 operatr - 一切正常。但我无法从代码创建这个实体:

public void insertNewOperator(OperatorsReportTable newOperator) {
em.getTransaction().begin();
try {
em.persist(newOperator);
} catch (Exception e) {
logger.log(Level.FINEST, "Exception in task time={0}. Exception message = {1}.", new Object[]{newOperator.getNickname(), e.getMessage()});
}
try {
em.getTransaction().commit();
em.clear();
} catch (Exception e) {
logger.log(Level.FINEST, "Exception in task time={0}. Exception message = {1}.", new Object[]{new Date(), e.getMessage()});
em.clear();
}
}

我有错误:

org.hibernate.PersistentObjectException: detached entity passed to persist: entety.LanguagesList

我认为这是因为语言表条目已经存在。我需要创建新的运算符并从语言表中设置 iD 并保存它。

最佳答案

如果您想保存 OperatorsReportTable 对象而不保存 LanguagesList 对象(因为它已经保存了),那么您必须使用 @ManyToOne

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "LANGUAGES_LIST_ID")
private LanguagesList languagesList;

此外,删除级联

关于java - 如果 ID 已存在,则将实体与另一个实体一起保存为属性时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34131940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com