gpt4 book ai didi

java - 多个主键表 - Hibernate NonUniqueObjectException

转载 作者:行者123 更新时间:2023-11-29 06:12:51 25 4
gpt4 key购买 nike

我有一个包含 2 个主键的表(所以它们的组合应该是唯一的)。架构是这样的:

TABLE="INVOICE_LOGS"
INVOICE_NUMBER PK non-null
INVOICE_TYPE PK non-null
AMOUNT

当我尝试一次保留多条记录时,出现此 hibernate 异常:

Caused by: javax.persistence.PersistenceException: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [...InvoiceLog#110105269]

所以如果我在下面使用下面的代码,我会得到上面的 hibernate 异常。如果我只保存一条记录,它工作正常,但如果我尝试像我正在尝试做的那样保存一个集合,它就会失败。

    List<InvoiceLog> logs = getLogs();
for(OvercounterLogDO log: logs) {
persist(log);
}

public void persist(final Object entity) {
entityManager.persist(entity);
entityManager.flush();
}

hibernate 映射类如下:

@Component(InvoiceLog.BEAN_NAME)
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Entity
@Table(name = "INVOICE_LOGS", uniqueConstraints = {@UniqueConstraint(columnNames = "INVOICE_NUMBER"),@UniqueConstraint(columnNames = "INVOICE_TYPE")} )
public class InvoiceLog implements java.io.Serializable {

private static final long serialVersionUID = -7576525197897271909L;

protected static final String BEAN_NAME = "invoiceLog";

private long invoiceNumber;
private String invoiceType;
private Double amount;

public InvoiceLog(){}

public InvoiceLog(Integer invoiceNumber, String invoiceType,
Double amount) {
super();
this.invoiceNumber = invoiceNumber;
this.invoiceType = invoiceType;
this.amount = amount;
}

@Id
@Column(name = "INVOICE_NUMBER", unique = true, nullable = false, precision = 10, scale = 0)
public long getInvoiceNumber() {
return invoiceNumber;
}
public void setInvoiceNumber(long invoiceNumber) {
this.invoiceNumber = invoiceNumber;
}

// @Id
@Column(name = "INVOICE_TYPE", nullable = false, length = 4)
public String getInvoiceType() {
return invoiceType;
}
public void setInvoiceType(String invoiceType) {
this.invoiceType = invoiceType;
}

@Column(name = "AMOUNT", nullable = false, length = 12)
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}

}

最佳答案

您当前的映射只有一个 ID、invoiceNumber,而不是复合键。因此,它会要求 invoiceNumber 是唯一的,而不是您想要的组合。这就是异常告诉您的内容,它注意到您正在尝试保存具有相同 Id 值的第二条记录。

您需要将这两个字段映射为一个组合键。从您对第二个 @Id 的注释看来,您在某个时候正朝那个方向前进。 Here's the documentation关于映射复合键的方法。

关于java - 多个主键表 - Hibernate NonUniqueObjectException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6204673/

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