我正在尝试将Javers与Spring Data REST项目集成。目前,我在域中拥有以下实体。
学生班
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private Long dob;
@OneToOne
private Gender gender;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "student", orphanRemoval = true)
private List<ContactNumber> contactNumbers = new ArrayList<>();
}
ContactNumber.class
@Entity
public class ContactNumber {
@Id
@GeneratedValue
private Long id;
private String phoneNumber;
private Boolean isPrimary;
@ManyToOne
private Student student;
}
在javers文档中提到:
在现实世界中,领域对象通常包含各种类型的噪声
您不想审核的属性,例如动态代理(例如
Hibernate延迟加载代理),重复数据,技术标志,
自动生成的数据等。
那么这是否意味着我在联系电话号码类别的
@DiffIgnore
学生字段或学生类别的@ManyToOne
联系人字段中放置了@OneToMany
? 最佳答案
这取决于您如何记录对象以及要记录的内容。考虑这两行(假设您在p和contactNumber之间具有链接)
//This logs p and contactNumber as part of the array part of p. If you want to ignore contactNumber here,
//add @DiffIgnore on the @OneToMany property. If you want to ignore
javers.commit("some_user", p);
//This would log contactNumber and p as the student. You can add @DiffIgnore here on the student property (@ManyToOne)
javers.commit("some_user", contactNumber);
请注意,还有另一个注释
@ShallowReference
,它将记录对象的ID,而不是记录整个对象。例如。如果将@ShallowReference添加到student
属性,它将不会记录整个Person对象,而只会记录其ID。您可以使用它代替这些对象之间的链接。更新:
查看您的模型,建议您删除
student
属性。从电话号码链接到学生没有任何意义。给学生分配了一个号码,而不是相反。因此,您的模型将如下所示。@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private Long dob;
@OneToOne
private Gender gender;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "student", orphanRemoval = true)
private List<ContactNumber> contactNumbers = new ArrayList<>();
}
ContactNumber.class
@Entity
public class ContactNumber {
@Id
@GeneratedValue
private Long id;
private String phoneNumber;
private Boolean isPrimary;
}
如果您确实需要查找以电话号码开头的人员/学生,则可以为您的人员类创建一个存储库,以便您进行搜索。看起来像这样:
//extend from the corresponding Spring Data repository interface based on what you're using. I'll use JPA for this example.
interface PersonRepository extends JpaRepository<Person, Long> {
Person findByPhoneNumber(String phoneNumber);
}
有了这个,您的模型就变得更干净了,您根本不需要使用DiffIgnore。