eclipselink jpa条件参考未映射列 [英] eclipselink jpa criteria reference unmapped column
问题描述
在编写jpql查询时,我可以使用COLUMN()引用未映射的列(我知道它是特定于eclipselink的)。
使用javax.persistence.criteria.CriteriaBuilder,javax.persistence.criteria.Predicate等构建条件时,有什么方法可以引用未映射的列?
when writing jpql queries I can reference not mapped columns with COLUMN() (I know it is eclipselink specific). Is there any way I can reference unmapped column when building criteria using javax.persistence.criteria.CriteriaBuilder, javax.persistence.criteria.Predicate, etc?
我面临的问题:我有带有全文搜索列的postgresql表。我不希望将其映射到实体对象,但我想在查询中使用它(并且我还需要使用CriteriaBuilder进行查询)。
The problem I am facing: I have postgresql table with full text search column. I do not want it to be mapped to entity objects but I qould like to use is in queries (and I need also queries using CriteriaBuilder).
编辑:代码示例
我有一张表格:X(id整数,名称varchar,fts tsvector)
I have a table: X (id integer, name varchar, fts tsvector)
fts列是全文搜索索引数据。
我需要没有 fts属性的实体类,例如:
"fts" column is full text search index data. I need entity class without "fts" attribute, like:
@Entity class X {
@Id Integer id;
@Column String name;
}
这样就永远不会获取fts数据(以提高性能),但是我需要能够查询该列。我可以使用jpql做到这一点:$ b $ b从X t选择X t WHERE COLUMN('fts',t)不为空;
so that fts data is never fetched (for performance), but I need to be able to query that column. I can do this with jpql: SELECT t FROM X t WHERE COLUMN('fts', t) IS NOT NULL;
但是如何引用这样建立类似以下条件的列:
but how can I reference such column when building criteria like:
Specification<Fts> spec = new Specification<Fts>() {
@Override
public Predicate toPredicate(Root<Fts> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
return builder.notNull(root.<String>get("fts"));
}
};
其他选择:
如何在实体类中添加引用表列但从不添加的属性拿来?我尝试添加@Basic(fetchType = FetchType.LAZY),但是它不起作用,并且在查询时获取了值...
other choice: How to add attribute in entity class that reference table column but is never fetched? I tried adding @Basic(fetchType = FetchType.LAZY) but it does not work and value is fetched upon query...
推荐答案
Ok. I managed to solve it this way:
Specification<Fts> spec = new Specification<Fts>() {
@Override
public Predicate toPredicate(Root<Fts> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
JpaCriteriaBuilder cb = (JpaCriteriaBuilder) builder;
List<String> args = new ArrayList();
args.add("FTS query");
javax.persistence.criteria.Expression<Boolean> expr = cb.fromExpression(
cb.toExpression(
cb.function("", Boolean.class, cb.fromExpression(((RootImpl) root).getCurrentNode().getField("fts")))
)
.sql("? @@ to_tsquery(?)", args)
);
// getField() allows to reference column not mapped to Entity
query.where(expr);
return null; // or return cb.isTrue(expr); and then not need to set query.where()
}
};
这篇关于eclipselink jpa条件参考未映射列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!