최대 절전 모드 엔티티를위한 공통 기본 클래스가 있습니까?
-
03-07-2019 - |
문제
최대 절전 모드 엔티티를위한 공통 기본 클래스가 있습니까? 즉 ID, 버전 및 기타 공통 속성이 포함 된 매핑 스케 클래스가 있습니까? 단점이 있습니까?
예시:
@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 및 생성 날짜뿐만 아니라 수정 날짜도 있습니다. 우리는 또한 중간체가 있습니다 taggedbaseentity 그것은 a 태그 가능 웹 애플리케이션 엔티티 중 일부는 스택 오버플로에 대한 질문과 같은 태그가 있기 때문에 인터페이스.
다른 팁
내가 사용하는 것은 주로 hashcode ()와 equals ()를 구현하는 것입니다. 또한 엔티티를 예쁘게 인쇄하는 방법을 추가했습니다. 위의 DR에 대한 응답으로,이 중 대부분은 무시할 수 있지만 내 구현에서는 유형의 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();
}
}
나는 공통 기본 클래스를 사용하는 것을 망설이지 않을 것입니다. 결국 O/R 매핑의 요점입니다.
나는 공통 기본 클래스도 사용하지만 엔티티가 적어도 일부 공통 속성을 공유하는 경우에만 가능합니다. ID가 유일한 공통 속성이라면 사용하지 않을 것입니다. 지금까지 나는 아무런 문제가 발생하지 않았습니다.
그것은 나에게도 잘 작동합니다.
이 엔티티에서 필요에 따라 최대 절전 모드 엔버와 같은 일부 이벤트 리스너 / 인터셉터를 추가하여 다음을 수행 할 수 있습니다. - 첫 번째 삽입 날짜를 자동으로 설정하고 그와 같은 것들 ...
여기에서 몇 가지 샘플을 찾을 수 있습니다
http://blogsprajeesh.blogspot.com/2010/01/nhibernate-defining-mappings-part-4.html