[英]How to have a calculated column in table using hibernate
I want to add to an existing entity a new Transient column that doesn't exist in the database and will be calculated when calling a query that fetches the table and fill the new column.我想向现有实体添加一个新的 Transient 列,该列在数据库中不存在,并且将在调用获取表并填充新列的查询时进行计算。
I tried the following:我尝试了以下方法:
for the following entity:对于以下实体:
A {
@Column
Integer x;
@Transient
Integer y;
}
I want to create a query that returns the result in A object:我想创建一个在 A 对象中返回结果的查询:
query (named readA): select x, 1 from A;
List<A> query = em().createNamedQuery('readA').getResultList();
My approach fails, any suggestions on how that can be done?我的方法失败了,关于如何做到这一点的任何建议?
Since you want this only for this one query, you should use a DTO projection with a dedicated query.由于您只希望此查询用于此查询,因此您应该使用带有专用查询的 DTO 投影。 You can make use of the JPQL constructor syntax for this.您可以为此使用 JPQL 构造函数语法。
Something like the following:类似于以下内容:
SELECT NEW com.mycompany.package.MyDto(alias.x, 1)
FROM A alias
You need a constructor in that class though that matches the use.尽管与使用匹配,但您需要该类中的构造函数。
Having said that, I think this is a perfect use case forBlaze-Persistence Entity Views .话虽如此,我认为这是Blaze-Persistence Entity Views的完美用例。
Blaze-Persistence is a query builder on top of JPA which supports many of the advanced DBMS features on top of the JPA model. Blaze-Persistence 是一个基于 JPA 的查询构建器,它支持基于 JPA 模型的许多高级 DBMS 功能。 I created Entity Views on top of it to allow easy mapping between JPA models and custom interface defined models, something like Spring Data Projections on steroids.我在它之上创建了实体视图,以允许在 JPA 模型和自定义接口定义模型之间轻松映射,例如类固醇上的 Spring Data Projections。 The idea is that you define your target structure the way you like and map attributes(getters) via JPQL expressions to the entity model.这个想法是您按照自己喜欢的方式定义目标结构,并通过 JPQL 表达式将属性(getter)映射到实体模型。 Since the attribute name is used as default mapping, you mostly don't need explicit mappings as 80% of the use cases is to have DTOs that are a subset of the entity model.由于属性名称用作默认映射,因此您通常不需要显式映射,因为 80% 的用例是具有作为实体模型子集的 DTO。
A projection with Entity Views could look as simple as the following带有实体视图的投影看起来很简单,如下所示
@EntityView(A.class)
interface MyDto {
long getX();
@Mapping("1") // This is where your JPQL expression goes
int getY();
}
Querying is a matter of applying the entity view to a query, the simplest being just a query by id.查询是将实体视图应用于查询的问题,最简单的只是按 id 查询。
MyDto dto = entityViewManager.find(entityManager, MyDto.class, id);
But the Spring Data integration allows you to use it almost like Spring Data Projections: https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features但是 Spring Data 集成允许您几乎像 Spring Data Projections 一样使用它: https : //persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features
List<MyDto> findAll();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.