我们是否有Hibernate实体的通用基类?
时间:2020-03-06 14:57:58 来源:igfitidea点击:
我们是否具有Hibernate实体的通用基类,即具有id,version和其他通用属性的MappedSuperclass?有什么缺点吗?
例子:
@MappedSuperclass()
public class BaseEntity {
private Long id;
private Long version;
...
@Id @GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {return id;}
public void setId(Long id) {this.id = id;}
@Version
public Long getVersion() {return version;}
...
// Common properties
@Temporal(TemporalType.TIMESTAMP)
public Date creationDate() {return creationDate;}
...
}
@Entity
public class Customer extends BaseEntity {
private String customerName;
...
}
解决方案
这对我们来说很好。除了ID和创建日期,我们还有一个修改日期。我们还具有一个实现Taggable接口的中间TaggedBaseEntity,因为我们的某些Web应用程序实体具有标签,例如有关Stack Overflow的问题。
毕竟,这就是O / R映射的重点。
我也使用通用的基类,但前提是这些实体至少共享一些通用的属性。如果ID是唯一的通用属性,我将不使用它。到现在为止,我还没有遇到任何问题。
我主要使用的是实现hashCode()和equals()的方法。我还添加了一种漂亮打印实体的方法。作为对以上DR的响应,可以覆盖其中的大多数,但是在我的实现中,我们会被困在Long类型的ID上。
public abstract class BaseEntity implements Serializable {
public abstract Long getId();
public abstract void setId(Long id);
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
return result;
}
/**
* @see java.lang.Object#equals(Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BaseEntity other = (BaseEntity) obj;
if (getId() == null) {
if (other.getId() != null)
return false;
} else if (!getId().equals(other.getId()))
return false;
return true;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return new StringBuilder(getClass().getSimpleName()).append(":").append(getId()).toString();
}
/**
* Prints complete information by calling all public getters on the entity.
*/
public String print() {
final String EQUALS = "=";
final String DELIMITER = ", ";
final String ENTITY_FORMAT = "(id={0})";
StringBuffer sb = new StringBuffer("{");
PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(this);
PropertyDescriptor property = null;
int i = 0;
while ( i < properties.length) {
property = properties[i];
sb.append(property.getName());
sb.append(EQUALS);
try {
Object value = PropertyUtils.getProperty(this, property.getName());
if (value instanceof BaseEntity) {
BaseEntity entityValue = (BaseEntity) value;
String objectValueString = MessageFormat.format(ENTITY_FORMAT, entityValue.getId());
sb.append(objectValueString);
} else {
sb.append(value);
}
} catch (IllegalAccessException e) {
// do nothing
} catch (InvocationTargetException e) {
// do nothing
} catch (NoSuchMethodException e) {
// do nothing
}
i++;
if (i < properties.length) {
sb.append(DELIMITER);
}
}
sb.append("}");
return sb.toString();
}
}
你可以在这里找到一些样品
http://blogsprajeesh.blogspot.com/2010/01/nhibernate-defining-mappings-part-4.html

