集的映射需要ID?

时间:2019-02-27 14:32:54

标签: java spring spring-data mapping spring-data-jdbc

我在使用spring数据jdbc时遇到映射问题,如下所示:
Student实体:

@Value(staticConstructor = "of")
public class Student {

private final @Id
@Wither
long studentId;

@NotNull
@Size(min = 4, max = 20)
private String userId;

@NotNull
@Min(0)
private int matriculationNumber;

@NotNull
@Email
private String eMail;

private @Wither
Set<StudentSubjectRegistration> studentSubjectRegistrations;
}

接下来,我有一个StudentSubjectRegistration实体:

@Value(staticConstructor = "of")
public class StudentSubjectRegistration {

@NotNull
private String electiveType;

@NotNull
private LocalDateTime created;

@NotNull
private long subjectid;
}

当我进行测试以找到一个特定的学生时,如下所示:

@Test
public void findOneStudent() throws InterruptedException, ExecutionException {
    long studentId = 2L;
    Future<Student> student = studentService.findById(2L);
    while (!student.isDone()) {
        Thread.sleep(100);
    }
    assertThat(student.get()).isNotNull();
    assertThat(student.get().getStudentId()).isEqualTo(studentId);
}

控制台说,发出了一条sql语句: Executing prepared SQL statement [SELECT student.studentid AS studentid, student.userid AS userid, student.matriculationnumber AS matriculationnumber, student.email AS email FROM student WHERE student.studentid = ?]

据我了解,应该发布另一个sql语句来获取相关的注册吗?

相反,发生了一种异常: java.lang.IllegalStateException: Required identifier property not found for class de.thd.awp.student.StudentSubjectRegistration!

我必须用StudentSubjectRegistration@Id建模吗?

StudentSubjectRegistration不应是聚合根。应该是Student的引用,其中保存了其注册。

我想念什么吗?

请进一步注意,我受此博客文章https://spring.io/blog/2018/09/27/what-s-new-in-spring-data-lovelace的启发而尝试建立实体不变性模型……

我做对了吗?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

集合中的实体需要一个effective-id,它在集合中必须是唯一的。

ListMap的情况下,它们是通过对聚合根和List / Map的索引/关键字的反向引用来构建的。

使用Set时,没有键,索引或类似键,因此,必须用@Id注释一个属性。

在您的情况下,subjectid听起来像一个有前途的候选人,假设Student不能两次注册同一主题。