具有@ManyToOne的两个实体应该加入同一个表

时间:2010-06-12 18:53:20

标签: java hibernate jpa many-to-one

我有以下实体

学生

@Entity
public class Student implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  //getter and setter for id

}

教师

@Entity
public class Teacher implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  //getter and setter for id

}

任务

@Entity
public class Task implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  @ManyToOne(optional = false)
  @JoinTable(name = "student_task", inverseJoinColumns = { @JoinColumn(name = "student_id") })
  private Student author;

  @ManyToOne(optional = false)
  @JoinTable(name = "student_task", inverseJoinColumns = { @JoinColumn(name = "teacher_id") })
  private Teacher curator;

  //getters and setters

}

考虑authorcurator已经存储在数据库中,并且两者都处于连接状态。我正试图坚持我的Task

Task task = new Task();
task.setAuthor(author);
task.setCurator(curator);
entityManager.persist(task);

Hibernate执行以下SQL:

insert 
  into
    student_task
    (teacher_id, id) 
  values
    (?, ?)

当然会导致null value in column "student_id" violates not-null constraint

任何人都可以解释这个问题以及解决问题的可能方法吗?

更新

请参阅下面我自己的解决方案。

2 个答案:

答案 0 :(得分:2)

我认为你错过了JoinColumns标签......

joinColumns = { @JoinColumn(name = "student_id", referencedColumnName = "id") }

joinColumns = { @JoinColumn(name = "teacher_id", referencedColumnName = "id") }

分别在作者和策展人中

还要记住,inversjoincolumn是拥有的表中的列..所以它必须是这样的:

inverseJoinColumns = {@JoinColumn(name="id")})

答案 1 :(得分:2)

我已在@SecondaryTable的帮助下解决了我的问题,并从@JoinTable切换到@JoinColumn

<强>任务

@Entity
@SecondaryTable(name="student_task")
public class Task implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  @ManyToOne(optional = false)
  @JoinColumn(table = "student_task", name = "student_id")
  private Student author;

  @ManyToOne(optional = false)
  @JoinColumn(table = "student_task", name = "teacher_id")
  private Teacher curator;

  //getters and setters

}

现在,生成的SQL看起来像:

insert 
  into
    student_task
    (student_id, teacher_id, id) 
  values
    (?, ?, ?)

一切正常:)