是否可以在单个实体内映射多个行?

时间:2018-06-16 04:22:16

标签: hibernate jpa associations

我想使用一个单独的实体类来保存关系。但是,我不知道我应该在StudentTest类中添加什么注释。

我尝试了几种方法(例如。ElementCollection),但我得到了No Persistence provider for EntityManager named mainDB。如果删除StudentTest类,则不会发生此错误。

或是否无法使用ListTest保留在StudentTest内?

这些是实体:

@Entity
@Table(name = "students")
public class Student {

  @Id
  @Column(name = "id")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(name = "name")
  private String name;
}

@Entity
@Table(name = "tests")
public class Test {

  @Id
  @Column(name = "id")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column(name = "mark")
  private int mark;

}

@Entity
@Table(name = "student_tests")
public class StudentTest {

  private Student student;

  private List<Test> test;

}

这些是表格模式:

CREATE TABLE students (
  id BIGINT(20) NOT NULL AUTO_INCREMENT,
  name VARCHAR(100) NOT NULL,
  PRIMARY KEY (id)
);

CREATE TABLE tests (
  id BIGINT(20) NOT NULL AUTO_INCREMENT,
  mark INT NOT NULL,
  PRIMARY KEY (id)
);

CREATE TABLE student_tests (
  student_id BIGINT(20),
  test_id BIGINT(20),
  PRIMARY KEY (student_id, test_id),
  FOREIGN KEY (student_id) REFERENCES students(id),
  FOREIGN KEY (test_id) REFERENCES tests(id)
);

更新:我尝试使用MapsId添加复合ID,但似乎没有帮助

@Entity
@Table(name = "student_tests")
public class StudentTest {

  @EmbeddedId
  private StudentTestId id;

  @ManyToOne
  @MapsId("studentId")
  private Student student;

  @OneToMany
  @MapsId("testId")
  private List<Test> test;
}

@Embeddable
public class StudentTestId implements Serializable {

  @Column(name = "student_id")
  private Long studentId;

  @Column(name = "test_id")
  private Long testId;
}

0 个答案:

没有答案