具有@ManyToOne的两个实体应加入同一张表 [英] Two entities with @ManyToOne should join the same table

查看:133
本文介绍了具有@ManyToOne的两个实体应加入同一张表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下实体

学生

@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已经存储在DB中,并且都处于附加状态.我正在尝试保留我的Task:

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执行以下SQL:

Hibernate executes the following SQL:

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

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

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

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

更新

请在下面查看我自己的解决方案.

See my own solution below.

推荐答案

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

I've resolved my issue with the help of @SecondaryTable and switched from @JoinTable to @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看起来像:

Now, generated SQL looks like:

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

一切正常:)

这篇关于具有@ManyToOne的两个实体应加入同一张表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆