gpt4 book ai didi

spring boot - 计算字段

转载 作者:行者123 更新时间:2023-12-04 20:31:28 25 4
gpt4 key购买 nike

所以,我有一个实体,它有字段 start_date (java.util.Date 是类型)。

我想要另一个字段,它会自动填充与开始日期对应的星期几(星期日为数字 1,星期一为数字 2 等)的整数。

这是我的实体的片段:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

@DateTimeFormat(pattern = "yyyy-MM-dd")
@Temporal(TemporalType.DATE)
private Date start_date;

我尝试通过以下方式添加计算字段:
@Column(name = "weekday")
@Formula("(select dayofweek(l.start_date) from Lesson l where l.id = id)")
private Integer weekDay;

但是,在 H2 控制台中查看类(class)表时,没有“工作日”这样的列

我还尝试了其他选项 - 没有 @Formula 注释和带有 start_date 参数的 setter,但我想这个 setter 永远不会被调用,因为“工作日”列填充了空值。
这是我尝试用作替代解决方案的二传手:
    public void setWeekDay(Date start_date) {
Calendar c = Calendar.getInstance();
c.setTime(start_date);
this.weekDay = c.get(Calendar.DAY_OF_WEEK);
}

很明显,我在这里遗漏了一些东西,可能是因为我还在学习 Spring Boot ......

总结一下 - 我想在表 Lesson 中有一个列,它是从同一个表的另一列计算出来的。

最佳答案

@Formula表示您的字段由您的规则计算。此实体字段不是数据库中的列。此字段按指定规则为每个实体计算加载时间。

如果注释@Column(name = "weekday")将在 @Formula 附近工作如果您期望加载的实体中的值与 DB 中的值相同,但这里计算的是一个且不同的(不一致的情况),您会感到非常困惑。

如果您想在此处保存来自 Lesson 的值您应该删除的表 @Formula并使用 @EntityListeners({YourEntityJpaCallbacksListener.class})在 Spring Bean YourEntityJpaCallbacksListener您可以定义标有 @PreUpdate 的方法或 @PrePersist并使用相应的操作将计算值设置为weekday .

例如:

@EntityListeners({YourEntityJpaCallbacksListener.class})
@Entity
public class YourEntity{
// your code
}

@Component
public class YourEntityJpaCallbacksListener {
@Autowired
private LessonRepository lessonRepository;

@PreUpdate
void preUpdate(YourEntity yourEntity) {
if (recurrentRuleRepository.exists(yourEntity.getId())) {
Integer weekDay = lessonRepository.findOne(yourEntity.getId());
yourEntity.setWeekDay(weekDay);
}
}

}

关于spring boot - 计算字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45323231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com