java - Hibernate注解与外键关系

标签 java hibernate jpa orm

我有一个像这样注释的域对象以支持 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?

不确定,因为它可能是 ManyToOneOneToOne,但我假设它是 ManyToOne:

@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="USERDETAILS_EMAIL_ID", referencedColumnName="EMAIL_ID")
private User userDetails;

fetch 注释元素用于演示目的,EAGER 实际上是默认值。 JoinColumn 中的 namereferencedColumn 注释元素也是可选的。以下是 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 than referencedColumnName) refer to this column and have the same semantics as for the Column 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/

相关文章:

java - 调整 Jframe 大小时如何停止自动重绘 ()

java - 结合 MDB、JPA 和 JTA

sql - 添加 hibernate 更新时为什么会出现排序规则冲突?

java - 在 Hibernate 中使用 `in()` 调用命名查询

java - JPQL/HQL - 是否可以通过提供 ID 列表来指定顺序?

java - 如何在android中的Activity之间传递集合

java - 自定义 addToDisplay 方法在另一个类中返回异常

java - Hibernate 3.5.1 的 Tomcat 错误

java - Hibernate Java 持久化来自持久化父类(super class)的子类实体

hibernate - JPA/Hibernate 提高批量插入性能