简体   繁体   中英

Hibernate - save return value of a method rather then the field

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM