Javers - 双向OneToMany上的DiffIgnore

时间:2018-01-15 12:46:31

标签: java spring hibernate spring-data-rest javers

我正在尝试将Javers与Spring Data REST项目集成。目前,我的域名中包含以下实体。

Student.class

@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 docs中提到:

  

在现实世界中,域对象通常包含各种嘈杂   您不想审核的属性,例如动态代理(例如   Hibernate延迟加载代理),重复数据,技术标志,   自动生成的数据等。

这是否意味着我在联系号码类的@DiffIgnore学生字段或学生班的@ManyToOne个联系人字段中添加了@OneToMany

1 个答案:

答案 0 :(得分:1)

这取决于您如何记录对象以及要记录的内容。考虑这两行(假设你有一个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;
}

如果您确实需要找到以电话号码开头的人/学生,您可以为您的Person类设置一个存储库,使您可以进行搜索。这看起来像这样:

//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。