[英]Hibernate calculated collection @Formula
is it possible to have and Entity with a field calculated using Formula
when the field is a Collection (let's say it's a Set
)? 当字段是Collection时(假设它是
Set
),是否可以通过Formula
计算出具有Entity的字段?
Here's the dummy example of what I'm trying to achive: 这是我要达到的目标的虚拟示例:
@Formula(value =
"SELECT NEW com.example.entity.Person(p.name, p.age) FROM Person p")
lateinit var people :Set<Person>
From the JavaDoc for @Formula
: 从JavaDoc中获取
@Formula
:
Defines a formula (derived value) which is a SQL fragment ...
定义一个公式(派生值),它是一个SQL片段 ...
You have to think of the fragment you write as an replacement in the select statement: 您必须考虑在select语句中编写的替换片段:
SELECT (formulaValue) AS propertyName FROM ....
Everything you can write into formulaValue
can be used in @Formula
. 你可以写成的一切
formulaValue
可以用在@Formula
。
Your example is not a valid SQL fragment and as you can see, it is not possible to return more than one value from a @Formula
. 您的示例不是有效的SQL片段,并且您可以看到,从
@Formula
返回多个值是@Formula
。
But you could use @Subselect
and a wrapper object instead: 但是您可以使用
@Subselect
和包装对象代替:
@Entity
@Subselect("SELECT name, age FROM Person p")
public class PersonWrapper {
@Id
private String name;
private int age;
}
(in Java, as I'm not aware of the correct syntax of Kotlin) (在Java中,因为我不了解Kotlin的正确语法)
If you really need the collection of these values in another entity, you need something to join on (which is missing in your example) and use that in an @OneToMany
or @ManyToMany
. 如果您确实需要在另一个实体中收集这些值,则需要加入一些东西(在示例中是缺少的)并在
@OneToMany
或@ManyToMany
使用它。 Otherwise there is no use to have all these values in your entity, as all entities would have the same collection. 否则,没有必要在您的实体中拥有所有这些值,因为所有实体将具有相同的集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.