提问者:小点点

使用@Filter和@FilterDef向@Subselect实体添加参数


我一直试图完成这里提到的同样的事情,但没有成功:在Spring boot中的@Subselect注释中将参数绑定到sql请求?

我试图将此子选择的结果限制为表2中的对象,这些对象具有object_type的特定值

这是我正在使用的实体:

@Entity
@Immutable
@Subselect("select t2.object_id as objectId, count(*) as count\n"
    + "\tFROM table1 t1\n"
    + "\tINNER JOIN table2 t2 on t1.primary_id = t2.token_id\n"
    + "\tGROUP BY t2.object_id")
@FilterDef(
    name = "objectTypeIdStrFilter",
    parameters = @ParamDef(name = "objectTypeIdStr", type = "int")
)
@Filter(
    name = "objectTypeIdStrFilter",
    condition = "t2.object_type = :objectTypeIdStr"
)
public class ObjectCountView {
    @Id
    Integer objectId;

    @Column
    Integer count;
}

然后,我尝试通过EntityManager进行类似这样的操作来启用过滤器:

final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
final CriteriaQuery<Tuple> criteriaQuery = cb.createTupleQuery();
// Omitting code here where we build out the query
Session session = entityManager.unwrap(Session.class);
session.enableFilter("objectTypeIdStrFilter").setParameter("objectTypeIdStr", CONSTANT_VALUE_HERE).validate();
final Query query = entityManager.createQuery(criteriaQuery);
final List<Tuple> results = query.getResultList();

但是,当执行查询时,我不会将任何WHERE子句添加到应用该过滤器的 SQL 语句中。


共1个答案

匿名用户

看起来解决方案是在@Subselect中添加过滤器变量,而不是添加@Filter注释:

@Entity
@Immutable
@Subselect("select t2.object_id as objectId, count(*) as count\n"
    + "\tFROM table1 t1\n"
    + "\tINNER JOIN table2 t2 on t1.primary_id = t2.token_id\n"
    + "\tWHERE t2.object_type = :objectTypeIdStrFilter.objectTypeIdStr\n"
    + "\tGROUP BY t2.object_id")
@FilterDef(
    name = "objectTypeIdStrFilter",
    parameters = @ParamDef(name = "objectTypeIdStr", type = "int")
)
public class ObjectCountView {
    @Id
    Integer objectId;

    @Column
    Integer count;
}