mr_*_*ite 5 spring hibernate spring-boot
因此,我有一个实体,该实体具有字段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;
Run Code Online (Sandbox Code Playgroud)
我尝试通过以下方式添加计算字段:
@Column(name = "weekday")
@Formula("(select dayofweek(l.start_date) from Lesson l where l.id = id)")
private Integer weekDay;
Run Code Online (Sandbox Code Playgroud)
但是,在H2控制台中查看“课程”表时,没有“工作日”这样的列
我还尝试了其他选项-不带@Formula批注,而带有使用start_date参数的setter,但是我猜想永远不会调用此setter,因为“工作日”列中填充了null。这是我尝试用作替代解决方案的设置器:
public void setWeekDay(Date start_date) {
Calendar c = Calendar.getInstance();
c.setTime(start_date);
this.weekDay = c.get(Calendar.DAY_OF_WEEK);
}
Run Code Online (Sandbox Code Playgroud)
很明显,我在这里缺少一些东西,这可能是因为我还在学习Spring boot ...
总结一下-我想在表Lesson中有一个列,该列是从同一表的另一列计算得出的。
@Formula
表示要根据您的规则计算的字段。该实体字段不是数据库中的列。该字段按照指定的规则计算每个实体的加载时间。
如果注释@Column(name = "weekday")
可以在附近工作,@Formula
如果您期望加载的实体中的值与数据库中的值相同,但这里计算的值不同(不一致的情况),您会感到非常困惑。
如果你想保存表中的值,Lesson
你应该删除@Formula
并使用@EntityListeners({YourEntityJpaCallbacksListener.class})
在spring bean中YourEntityJpaCallbacksListener
,你可以定义标有@PreUpdate
or的方法@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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1823 次 |
最近记录: |