我有一个像这样注释的域对象以支持 hibernate 。
@Entity
@Table(name = "INPUT")
public class AppInput {
/**
* Unique id for this request
*/
@Id
@GeneratedValue
@Column(name = "INPUT_ID")
private long requestId;
/**
*
*/
@Column(name = "EMAIL_ID")
private String emailId;
/**
*
*/
@Column(name = "REQUEST_DATE")
private Date requestDate;
/**
*
*/
@Column(name = "INPUT_STATUS")
private char status;
/**
*
*/
@Column(name = "EXPECTED_ORDER_DATE")
private Date expectedOrdDt;
//Getter and setters
}
属性 emailId 是一个外键,引用 User 表中的 emailId 列。假设我将这样的属性添加到 AppInput.java
私有(private)用户用户详细信息;
我如何对此进行注释,以便每当我从数据库中获取 AppInput 时,相应的用户详细信息也会被填充?
最佳答案
The property emailId is a foreign key referring to say emailId column in User table.
然后不要添加emailId
属性,添加一个User
。
(...) How do i annotate this so that, whenever i fetch AppInput from db, the corresponding user details also get populated?
不确定,因为它可能是 ManyToOne
或 OneToOne
,但我假设它是 ManyToOne
:
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="USERDETAILS_EMAIL_ID", referencedColumnName="EMAIL_ID")
private User userDetails;
fetch
注释元素用于演示目的,EAGER
实际上是默认值。 JoinColumn
中的 name
和 referencedColumn
注释元素也是可选的。以下是 JPA 规范的简短摘要:
11.1.21 JoinColumn Annotation
The
JoinColumn
annotation is used to specify a column for joining an entity association or element collection.Table 20 lists the annotation elements that may be specified for the
JoinColumn
annotation and their default values.If the
JoinColumn
annotation itself is defaulted, a single join column is assumed and the default values described in Table 20 apply.The
name
annotation element defines the name of the foreign key column. The remaining annotation elements (other thanreferencedColumnName
) refer to this column and have the same semantics as for theColumn
annotation.If the
referencedColumnName
element is missing, the foreign key is assumed to refer to the primary key of the referenced table.
有关完整详尽的详细信息,请参阅规范中的表 20。
关于java - Hibernate注解与外键关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3350922/