Two entities with @ManyToOne should join the same table

Posted by Ivan Yatskevich on Stack Overflow See other posts from Stack Overflow or by Ivan Yatskevich
Published on 2010-06-12T18:53:19Z Indexed on 2010/06/12 22:42 UTC
Read the original article Hit count: 262

Filed under:
|
|
|

I have the following entities

Student

@Entity
public class Student implements Serializable {

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

  //getter and setter for id

}

Teacher

@Entity
public class Teacher implements Serializable {

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

  //getter and setter for id

}

Task

@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

}

Consider that author and curator are already stored in DB and both are in the attached state. I'm trying to persist my Task:

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

Hibernate executes the following SQL:

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

which, of course, leads to null value in column "student_id" violates not-null constraint

Can anyone explain this issue and possible ways to resolve it?

© Stack Overflow or respective owner

Related posts about java

Related posts about hibernate