可以将方法的返回值存储在数据库中,而不需要相应的属性吗?

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

Is it possible to store a method return value in the database without having a corresponding attribute?

问题

让我们假设我有以下类。

@Entity
public class ShiftDetail {
  @Id
  private Integer id = null;
  private String name = null;

  private LocalTime startTime = null;
  private LocalTime endTime = null;

  public Duration getShifDurationInSeconds() {
    return Duration.between(this.startTime, this.endTime).toSeconds();
  }
}

为了使一些未来的处理更加方便,我想将派生值“ShiftDurationInSeconds”存储在数据库中。

是否可以在不在类中创建属性的情况下使用JPA/ Hibernate来实现这一点?

英文:

Let's say I have the following class.

@Entity
public class ShiftDetail {
  @Id
  private Integer id = null;
  private String name = null;

  private LocalTime startTime = null;
  private LocalTime endTime = null;

  public Duration getShifDurationInSeconds() {
    return Duration.between(this.startTime, this.endTime).toSeconds();
  }
}

For making some down-the-line processing easier, I would like to store the derived value "ShiftDurationInSeconds" in the database.

Is there a way to do this with JPA/ Hibernate without creating an attribute in the class?

答案1

得分: 2

你可以使用 @PreUpdate@PrePersist 来在数据库中计算字段的持久性。

private long shiftDurationInSeconds;

@PreUpdate
@PrePersist
public void calShiftDurationInSeconds() {
    shiftDurationInSeconds = Duration.between(this.startTime, this.endTime).getSeconds();
}
英文:

You can use @PreUpdate and @PrePersist for calculate field persist in database.

private long shiftDurationInSeconds;

@PreUpdate
@PrePersist
public void calShiftDurationInSeconds() {
    shiftDurationInSeconds = Duration.between(this.startTime, this.endTime).getSeconds();
}

huangapple
  • 本文由 发表于 2020年7月30日 02:18:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63160043.html
匿名

发表评论

匿名网友

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

确定