Hibernate – 保存方法的返回值而不是字段

huangapple go评论144阅读模式
英文:

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 = &quot;commands&quot;)
public class Command {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = &quot;command&quot;)
private String command;

@Transient
private List&lt;String&gt; validResultList = new ArrayList&lt;&gt;();

public List&lt;String&gt; getValidResultList() {
    return validResultList;
}

public void setValidResultList(List&lt;String&gt; validResultList) {
    this.validResultList = validResultList;
}

@Column(name = &quot;valid_commands&quot;)
public String getValidResultListAsString() {
    StringBuilder sb = new StringBuilder();
    for (String value : validResultList) {
        sb.append(value).append(&quot; &quot;);
    }
    return sb.toString();
}

}

The field "valid_commands" is VARCHAR2.

For example:

Command comm1 = new Command(&quot;echo test;&quot;);
comm1.setValidResultList(Arrays.asList(&quot;foo&quot;, &quot;bar&quot;));

And it should save as:

&quot;foo bar &quot;

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.

huangapple
  • 本文由 发表于 2020年3月15日 06:19:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/60687816.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定