在我的应用程序架构中,我通常将对象或对象列表从数据访问层通过服务层发送到 Web 层,其中这些对象从DAO对象转换为DTO对象,反之亦然。Web 层无权访问 DAO 对象,并且 DAO 层不使用 DTO。
为了演示,我通常将代码编写为:
@Transactional(readOnly = true)
public List<UserDTO> getAllUserAsUserDTO() {
List<UserDTO> userDTOs = new ArrayList<UserDTO>();
for(User user : getAllUser()) {
userDTOs.add(constructUserDTO(user));
}
return userDTOs;
}
private UserDTO constructUserDTO(User user) {
UserDTO userDTO = new UserDTO();
userDTO.setFullName(user.getFullName());
userDTO.setId(user.getId());
userDTO.setUsername(user.getUsername());
userDTO.setRole(user.getRole());
userDTO.setActive(user.isActive());
userDTO.setActiveText(user.isActive() ? "Active" : "Inactive");
return userDTO;
}
这里用户是数据库实体:
@javax.persistence.Entity
@Table(name = "USER")
public class User extends Entity {
@Transient
private static final long serialVersionUID = -112950002831333869L;
private String username;
private String fullName;
private boolean active;
private String role;
// other fields
public User() {
super();
}
@NaturalId
@Column(name = "USERNAME", nullable = false)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name = "FULL_NAME")
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
@Column(name = "ACTIVE", nullable = false)
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
@Column(name = "ROLE")
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
这是 UserDTO:
public class UserDTO extends BaseDTO {
private static final long serialVersionUID = -3719463614753533782L;
private String username;
private String fullName;
private String role;
private String activeText;
private Boolean active;
//other properties
public UserDTO() {
super();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getActiveText() {
return activeText;
}
public void setActiveText(String activeText) {
this.activeText = activeText;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
}
所以我想知道这是否是在两个对象之间复制属性的唯一方法。我想我不确定。我也在使用lambdaj,那么这个 API 中是否有一种方法可以复制所有这些属性来创建其他对象的列表?
这个话题可能听起来很主观,但我真的很想从各位专家那里了解如何在最大字段具有相同字符串的情况下将对象从一种形式转换为另一种形式。