de.thksystems.persistence.hibernate.IdentifiedEntity Maven / Gradle / Ivy
/*
* tksCommons / mugwort
*
* Author : Thomas Kuhlmann (ThK-Systems, http://www.thk-systems.de) License : LGPL (https://www.gnu.org/licenses/lgpl.html)
*/
package de.thksystems.persistence.hibernate;
import java.io.Serializable;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import org.apache.commons.lang3.ClassUtils;
import de.thksystems.util.lang.ObjectUtils;
/**
* Identified entities have an ID, can be compared to each other and have a toString() method.
*/
@MappedSuperclass
public abstract class IdentifiedEntity implements Serializable, Comparable {
private static final long serialVersionUID = 5968828150324034087L;
@Id
@GeneratedValue
private long id;
public Long getId() {
return id;
}
protected void setId(long id) {
this.id = id;
}
/** Returns short class name appended with unique business key, e.g. "Order: 00002" or "Customer: [email protected]". */
public String asBusinessString() {
return ClassUtils.getShortClassName(this, null) + ": " + getUniqueBusinessKey();
}
/**
* Business key must identify the object for its business, e.g. an order code or a customer number, and must be unique.
*/
protected String getUniqueBusinessKey() {
return getId().toString();
}
@Override
public String toString() {
return ObjectUtils.buildToStringReflectiveConsideringAnnotations(this);
}
@Override
public int hashCode() {
if (getId() != null) {
return getId().intValue();
}
return ObjectUtils.buildHashCodeReflectiveConsideringAnnotations(this);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof IdentifiedEntity)) {
return false;
}
if (((IdentifiedEntity) obj).getId() == null || this.getId() == null) {
return obj.getClass().equals(this.getClass()) && ObjectUtils.buildEqualsReflectiveConsideringAnnotations(this, obj);
}
return (obj.getClass() == this.getClass() && ((IdentifiedEntity) obj).getId().longValue() == this.getId().longValue());
}
@Override
public int compareTo(IdentifiedEntity obj) {
if (getId() == null) {
if (obj.getId() == null) {
return 0;
} else {
return -1;
}
}
if (obj.getId() == null) {
return 1;
}
return getId().compareTo(obj.getId());
}
}