[英]Compare JPA Entity and DTO
我需要一種標准方法來將 JPA 實體與其 DTO 進行比較,並確定它們是否代表相同的業務 object。 我可以想到三種方法,每個 DTO 上的自定義方法,與 static 方法或比較器的接口。
在嘗試了不同的實現和測試之后,我的偏好是:
這些方法的任何其他優點/缺點或對其他方法的建議?
感謝您閱讀和思考我的問題!
背景
實體
數據庫鍵
在 ORM 和確定相等性的數據庫( equals()
/ hashcode()
)處唯一強制執行的業務密鑰
公共屬性(姓名、地址、年齡等)
非公開/機密屬性(密碼、刷新令牌、SSN 等)
@Data @EqualsAndHashCode(onlyExplicitlyIncluded = true) @Entity @Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "businessKey1", "businessKey2" }) }) class UserEntity { @Id Long id; @NotNull @EqualsAndHashCode.Include Long businessKey1; @NotNull @EqualsAndHashCode.Include Long businessKey2; String name; Integer age; String password; String refreshToken; String SSN; }
DTO(滿)
確定相等性的業務密鑰( equals()
/ hashcode()
)
公共屬性(姓名、地址、年齡等)
@Data @EqualsAndHashCode(onlyExplicitlyIncluded = true) class UserDto { @EqualsAndHashCode.Include @NotNull Long businessKey1; @EqualsAndHashCode.Include @NotNull Long businessKey2; String name; String address; Integer age; }
DTO(有限)
確定相等性的業務密鑰( equals()
/ hashcode()
)
選定的公共屬性(名稱)
@Data @EqualsAndHashCode(onlyExplicitlyIncluded = true) class UserNameDto { @EqualsAndHashCode.Include @NotNull Long businessKey1; @EqualsAndHashCode.Include @NotNull Long businessKey2; String name; }
方法 1 - 添加到每個 User*Dto 的自定義方法
boolean businessKeysMatch(UserEntity entity) {
if((this.getBusinessKey1() == entity.getBusinessKey1()) && (this.getBusinessKey2() == entity.getBusinessKey2()))
return true;
return false;
}
方法 2 - 將 static 方法添加到公共接口
interface UserKeys {
Long getBusinessKey1();
Long getBusinessKey2();
static boolean businessKeysMatch(UserKeys o1, UserKeys o2) {
if((o1.getBusinessKey1() == o2.getBusinessKey1()) && (o1.getBusinessKey2() == o2.getBusinessKey2()))
return true;
return false;
}
}
class UserEntity implements UserKeys {
// no other changes
}
class UserDto implements UserKeys {
// no other changes
}
class UserEntity implements UserKeys {
// no other changes
}
方法 3 - 比較器
interface UserBusinessKey {
Long getBusinessKey1();
Long getBusinessKey2();
}
class UserDto implements UserCompare {
// no other changes
}
class UserEntity implements UserCompare {
// no other changes
}
class UserCompare implements Comparator<UserBusinessKey> {
public int compare(UserBusinessKey o1, UserBusinessKey o2) {
int key1Compare = o1.getBusinessKey1().compareTo(o2.getBusinessKey1());
if (key1Compare == 0)
return o1.getBusinessKey2().compareTo(o2.getBusinessKey2());
return key1Compare;
}
}
如果您有多個User*Dto
,我將創建一個抽象AbstractUserDto
,然后由您所有具體的 User DTO 擴展。 您可以在那里放置您在方法 1 中顯示的方法(這樣您就不會一遍又一遍地重復相同的代碼):
@Data
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public abstract class AbstractUserDto {
@EqualsAndHashCode.Include
@NotNull
Long businessKey1;
@EqualsAndHashCode.Include
@NotNull
Long businessKey2;
String name;
public final boolean businessKeysMatch() {
return (this.getBusinessKey1() == entity.getBusinessKey1()) && (this.getBusinessKey2() == entity.getBusinessKey2());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.