Java 如何创建 DTO 类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6463634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create DTO class
提问by Raje
I want to create DTO class for User. my input to program is firstname, lastname,lastname.role,group1,group2,group3.
我想为用户创建 DTO 类。我对程序的输入是 firstname, lastname,lastname.role,group1,group2,group3。
so for each user role consist of group_1,group_2,group_3.....
所以对于每个用户角色包括 group_1,group_2,group_3.....
In database i want to store in following format demo,demo,demo,roleId, gorup_1_name group_1_Id demo,demo,demo,roleId, gorup_2 and group_2_Id demo,demo,demo,roleId, gorup_3 and group_3_Id
在数据库中我想以以下格式存储 demo,demo,demo,roleId, gorup_1_name group_1_Id demo,demo,demo,roleId, gorup_2 and group_2_Id demo,demo,demo,roleId, gorup_3 and group_3_Id
I was able separate all this things , but i want to assign this value to userDTO class and stored into database. basically im new to core java part. so how can create structure for this?
我能够将所有这些东西分开,但我想将此值分配给 userDTO 类并存储到数据库中。基本上我是核心java部分的新手。那么如何为此创建结构?
采纳答案by maasg
A Data Transfer Object (DTO) class is a java-bean like artifact that holds the data that you want to share between layer in your SW architecture.
数据传输对象 (DTO) 类是一个类似于 java bean 的工件,它保存您希望在软件架构中的层之间共享的数据。
For your usecase, it should look more or less like this:
对于您的用例,它应该或多或少是这样的:
public class UserDTO {
String firstName;
String lastName;
List<String> groups;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<String> getGroups() {
return groups;
}
public void setGroups(List<String> groups) {
this.groups = groups;
}
// Depending on your needs, you could opt for finer-grained access to the group list
}
回答by Jonathan
One thing to add:
补充一件事:
The essence of a DTO is that it transfersdata across the wire. So it will need to be Serializable.
DTO 的本质是通过网络传输数据。所以它需要是可序列化的。