英文:
Hibernate - save return value of a method rather then the field
问题
我想将列表中的所有字符串值保存到数据库中作为一个字符串。如果按照下面的实现,它会保存空值。是否有任何方法可以保存方法的返回值,而不是字段本身?
@Entity
@Table(name = "commands")
public class Command {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "command")
private String command;
@Transient
private List<String> validResultList = new ArrayList<>();
public List<String> getValidResultList() {
return validResultList;
}
public void setValidResultList(List<String> validResultList) {
this.validResultList = validResultList;
}
@Column(name = "valid_commands")
public String getValidResultListAsString() {
StringBuilder sb = new StringBuilder();
for (String value : validResultList) {
sb.append(value).append(" ");
}
return sb.toString();
}
}
字段 "valid_commands" 是 VARCHAR2。
例如:
Command comm1 = new Command("echo test;");
comm1.setValidResultList(Arrays.asList("foo", "bar"));
应该保存为:
"foo bar "
英文:
I want to save all String values of the list into the database as one String. If implemented as bellow it saves null value. Is there any way how to save a return value of method instead of the fiels itself?
@Entity
@Table(name = "commands")
public class Command {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "command")
private String command;
@Transient
private List<String> validResultList = new ArrayList<>();
public List<String> getValidResultList() {
return validResultList;
}
public void setValidResultList(List<String> validResultList) {
this.validResultList = validResultList;
}
@Column(name = "valid_commands")
public String getValidResultListAsString() {
StringBuilder sb = new StringBuilder();
for (String value : validResultList) {
sb.append(value).append(" ");
}
return sb.toString();
}
}
The field "valid_commands" is VARCHAR2.
For example:
Command comm1 = new Command("echo test;");
comm1.setValidResultList(Arrays.asList("foo", "bar"));
And it should save as:
"foo bar "
Would be glad for any tips.
答案1
得分: 0
只需定义一个名为"validResultListAsString"的字段,并在setValidResultList中设置其值,并通过getValidResultListAsString返回。此外,不应同时使用字段和属性注释。
英文:
Simply, define a filed named "validResultListAsString" and set its value at setValidResultList and return it by getValidResultListAsString. In addition, you shouldn't use filed and property annotations together.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论