Hibernate为equals实体自动生成的值

时间:2019-01-29 22:48:38

标签: hibernate

我在休眠时为实体使用自动生成的ID。 我希望为equals实例生成相同的ID。 在这里,我创建了两个equals对象,并将它们之一添加到其他休眠实体中,并同时保留了这两个对象。我希望它们的ID应该相等。

我该怎么办?

    @Entity
    @Table(name = "some_entity", uniqueConstraints = {})
    public class SomeEntity {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Integer id;

        String fullName;


        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            SomeEntity someEntity = (SomeEntity ) o;
            return Objects.equals(fullName, someEntity .fullName);
        }

        @Override
        public int hashCode() {
            return Objects.hash(fullName);
        }
    }

@Entity
@Table(name = "other_object")
public class OtherObject{


    @ManyToOne(cascade = {}, fetch = FetchType.LAZY)
    @JoinColumn(name = "some_entity1_id")
    private SomeEntity some_entity;

    @ManyToOne(cascade = {}, fetch = FetchType.LAZY)
    @JoinColumn(name = "some_entity2_id")
    private SomeEntity some_entity2;
}

someEntity1 = new SomeEntity("fullName1");
someEntity1shouldEqual = new SomeEntity("fullName1");
someEntity2 = new SomeEntity("fullName2");
otherObject = new OtherObject(someEntity1shouldEqual ,someEntity2);
db.persist(someEntity1);
db.persist(otherObject);
//expected true-
someEntity1.id = someEntity1shouldEqual.id 

0 个答案:

没有答案