开发者

Implementing equals/hashCode using a referenced ManyToOne entity

Assume we have following JPA Entities:

class Parent {
    @Id
    private Long id;
}

class Child {
    @Id
    private Long id;

    @Column
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    private Parent parent;
}

Let's assume a Child can uniquely be identified by its name on the Parent (combination of both). So, Parent and name can be considered as the business key of a Child.

I am unsure now what the best approach would be to implement equals (and hashCode) on the class Child.

Reference the id of the application

Since the Application proxy will be loaded and its id will be set on the proxy so the Application entity itself would not be initialized:

public boolean equals (Object o) {
    //null check, instanceof check ...
    return new EqualsBuilder().append(getName(), other.开发者_如何转开发getName())
            .append(getParent().getId(), other.getParent().getId())
            .isEquals(); 

}

This will do the trick but I see some downsides as well. First (minor), an extra not null check on the parent would probably be advisable which makes your equals methods less compound.

Next (less minor), This would required hibernate to access the properties rather than the fields; so, I would need to set the annotations on the getters instead of on the fields. This is something I can live with personally but the habit in the current project is to put the annotations on field level.

Don't use the referenced entity for evaluating equality

Ok, but then I need something else. I don't want to use the id of the Child (bad practice) which leaves me with only 1 option: using a separate property for this, like a UUID. I have nothing against the use of UUID's but of course only if there is no other option available.

My questions are:

  1. Did I miss an option?
  2. What, in your opinion, would be the advised way of doing this?


Another possibility would be to add another field containing the foreign key to the parent which can then be used in the equals and hashCode methods without fetching the referenced entity:

@Column(name="parent_id", insertable=false, updatable=false)
private String parentId;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="parent_id")
private Parent parent;


If you can get hold of the EntityManagerFactory (and if you can get hold of the EntityManager, EntityManager.getEntityManagerFactory() is one way to do it), another way to get the parent's ID is with:

emf.getPersistenceUnitUtil().getIdentifier(parent);

You'd still need a null check, though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜