以下情况:当我尝试保存带有 @EmbeddedId 字段的实体时,hibernate 使该字段从基类“mandant”变为“contact_mandant”,并抛出无效标识符错误。表“Contact”中的列名称是“mandant”,而不是“contact_mandat”。 我只是不明白为什么字段名称会自动更改。 这里有一些代码:
@MappedSuperclass
public abstract class BaseId implements Serializable {
@Column(name = "Mandant", precision = 2, nullable = false)
protected Byte mandant;
...getter, setter...
}
@Embeddable
public class ContactId extends BaseId implements Serializable {
@Column(name = "Id_Contact", precision = 9)
private Long id;
...getter, setter...
}
@Entity
public class Contact extends Base {
@EmbeddedId
private ContactId contactId;
...getter, setter...
}
@Entity(name = "Employee")
public class Employee extends Base {
@EmbeddedId
private EmployeeId id;
@MapsId("contactId")
@JoinColumns(value = {
@JoinColumn(referencedColumnName = "Mandant"),
@JoinColumn(referencedColumnName = "Id_Contact")
})
@OneToOne(fetch = FetchType.LAZY)
private Contact contact;
...getter, setter...
}
@Embeddable
public class EmployeeId extends BaseId implements Serializable {
@Column(name = "Id_Employee", precision = 9)
private Long id;
private ContactId contactId;
...getter, setter...
}
我来自 .Net 世界,对 JPA 还不太熟悉。有人可以友好地提示我做错了什么或者问题出在我的实现上吗?
最诚挚的问候 新闻记者
附注:Spring 4 和 Hibernate 5
最佳答案
使用共享复合 key 的解决方案:
@MapsId 中如果没有“id”,框架会生成以下查询:
“插入 EMPLOYEE_DETAILS (AEN_DATUM、SACHB_KZ、DETAILS、employee_id_employee、employee_MANDANT) 值 (?, ?, ?, ?, ?)”
将“id”添加到@MapsId后,查询为:
“插入 EMPLOYEE_DETAILS (AEN_DATUM、SACHB_KZ、DETAILS、id_employee、MANDANT) 值 (?, ?, ?, ?, ?)”
@Entity(name = "Employee")
@Table(name = "EMPLOYEE")
public class Employee extends Base {
@EmbeddedId
private EmployeeId id;
@Column(name = "FIRST_NAME", length = 100, nullable = false)
private String firstName;
@Column(name = "SUR_NAME", length = 100, nullable = false)
private String surName;
...
}
@Embeddable
public class EmployeeId extends BaseId implements Serializable {
@Column(name = "id_employee", precision = 9)
private Long employeeId;
...
}
@Entity(name = "EmployeeDetails")
@Table(name = "EMPLOYEE_DETAILS")
public class EmployeeDetails extends Base {
@EmbeddedId
private EmployeeId id;
@Column(name = "DETAILS", nullable = false)
private String details;
@MapsId("id")
@OneToOne
private Employee employee;
...
}
这与上面的实现不同,但问题是一样的。该查询是使用 CONTACT_MANDANT 而不是 MANDANT 生成的。
和平
关于java - JPA/hibernate 。如何防止自动继承字段get的类前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50743820/