首页 > 解决方案 > Conditionally assigning a table column to a property in spring

问题描述

I am new to spring and was wondering if there was a way to conditionally map a property. For example, if column a has a value of 0, use column b as the value, else default to a.

I was thinking something along the lines of

@Column(name="ColumnA" > 0 ? "ColumnA" : "ColumnB")
private Integer myValue;

If anybody could help steer me in the right direction, that would be great!

标签: javaspring

解决方案


当您使用 Spring 时,您可能正在导入 Hibernate 实现,因此这是@Formula注释(文档)的一个很好的用例。

定义一个公式(派生值),它是一个 SQL 片段,在大多数情况下充当 @Column 替代项。

@Formula注释接受 native ,因此对于这种SQL逻辑,您应该使用aSWITCHSQLfunction 。COALESCE

例子:

@Formula("case when ColumnA > 0 then ColumnA else ColumnB end")
private Integer myValue;

推荐阅读