在自定义方法equals中发现的问题,慎用对象的私有属性。
下面的类是所有实体(jpa entity)的父类,所有实体的比较都有该类实现。
当使用延迟加载时会出现问题,延迟加载时比较的并不是实体本身,而是实体的拦截实例,他是实体的子类,
other.id并没有值,正常情况下是通过other.getId()来访问id的,拦截实例会调用他包装的实体类的getId()。
?
??? @ManyToOne(fetch=FetchType.LAZY)
??? @JoinColumn(name = "SERIESTYPE_SEQ")
??? private SeriesType seriesType;
public abstract class BaseEntity implements Serializable
?
??? private Long id;
??? public Long getId() {
??? ??? return id;
??? }
??? public void setId(Long id) {
??? ??? this.id = id;
??? }
有bug的方法
@Override
??? public boolean equals(Object obj) {
??? ??? if (this == obj)
??? ??? ??? return true;
??? ??? if (obj == null)
??? ??? ??? return false;
??? ??? if (!(obj instanceof BaseEntity))
??? ??? ??? return false;
??? ??? final BaseEntity other = (BaseEntity) obj;
??? ??? if (getId() == null) {
??? ??? ??? if (other.getId() != null){
??? ??? ??? ??? return false;??? ??? ??? ???
??? ??? ??? }
??? ??? } else{
??? ??? ??? if (!getId().equals(other.id)){
??? ??? ??? ??? return false;
??? ??? ??? }
??? ??? }
??? ??? ???
??? ??? return true;
??? }
修改过后的方法
@Override
??? public boolean equals(Object obj) {
??? ??? if (this == obj)
??? ??? ??? return true;
??? ??? if (obj == null)
??? ??? ??? return false;
??? ??? if (!(obj instanceof BaseEntity))
??? ??? ??? return false;
??? ??? final BaseEntity other = (BaseEntity) obj;
??? ??? if (getId() == null) {
??? ??? ??? if (other.getId() != null){
??? ??? ??? ??? return false;??? ??? ??? ???
??? ??? ??? }
??? ??? } else{
??? ??? ??? if (!getId().equals(other.getId())){
??? ??? ??? ??? return false;
??? ??? ??? }
??? ??? }
??? ??? ???
??? ??? return true;
??? }
要避免直接使用对象的私有属性