Skip to content

Instantly share code, notes, and snippets.

@debop
Created November 13, 2013 00:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save debop/7441559 to your computer and use it in GitHub Desktop.
Save debop/7441559 to your computer and use it in GitHub Desktop.
package kr.hconnect.data.model;
import com.google.common.base.Objects;
import kr.hconnect.core.tools.HashTool;
import lombok.Getter;
import lombok.Setter;
/**
* Hibernate, JPA 의 모든 엔티티의 기본 클래스입니다.
*
* @author 배성혁 sunghyouk.bae@gmail.com
* @since 13. 6. 30. 오후 1:03
*/
@Getter
@Setter
abstract public class EntityBase<TId> extends PersistentObjectBase implements Entity<TId> {
abstract public TId getId();
@Override
@SuppressWarnings("unchecked")
public boolean equals(Object obj) {
boolean isSampeType = (obj != null) && getClass().equals(obj.getClass());
if (isSampeType) {
Entity<TId> entity = (Entity<TId>) obj;
return hasSameNonDefaultIdAs(entity) ||
((!isPersisted() || !entity.isPersisted()) && hasSameBusinessSignature(entity));
}
return false;
}
@Override
public int hashCode() {
return (getId() == null) ? System.identityHashCode(this)
: HashTool.compute(getId());
}
private boolean hasSameNonDefaultIdAs(Entity<TId> entity) {
if (entity == null) return false;
TId id = getId();
TId entityId = entity.getId();
return (id != null) && (entityId != null) && (id.equals(entityId));
}
private boolean hasSameBusinessSignature(Entity<TId> other) {
boolean notNull = (other != null);
int hash = (getId() != null) ? HashTool.compute(getId()) : hashCode();
if (notNull) {
int otherHash = (other.getId() != null) ? HashTool.compute(other.getId()) : other.hashCode();
return hash == otherHash;
}
return false;
}
@Override
public Objects.ToStringHelper buildStringHelper() {
return super.buildStringHelper()
.add("id", getId());
}
private static final long serialVersionUID = -4403625911423688674L;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment