views:

78

answers:

2

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?

UPDATE

See my own solution below.

A: 

I think you are missing the JoinColumns tag...

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

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

in author and curator respectively

Also remember, that the inversjoincolumn is the column in the owned table.. so it must be something like:

inverseJoinColumns = {@JoinColumn(name="id")})
Garis Suero
I'm sorry, but this doesn't work for my case. However, I've managed to resolve the issue using @SecondaryTable.
Ivan Yatskevich
+1  A: 

I've resolved my issue with the help of @SecondaryTable and switched from @JoinTable to @JoinColumn:

Task

@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

}

Now, generated SQL looks like:

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

and everything works just fine :)

Ivan Yatskevich