spring – QueryDSL动态谓词

我需要QueryDSL查询的帮助.我在Spring Data JPA中使用这个库.
我的服务类:

@Service("tblActivityService")
public class TblActivityService implements AbstractService<TblActivity> {

@Resource
private TblActivityRepository tblActivityRepository;

@Override
public List<TblActivity> findAll(Predicate predicate) {
    return (List<TblActivity>) tblActivityRepository.findAll(predicate);
}
}

我有动态的过滤器列表:

@Entity
@Table(name = "sys_filters")
public class SysFilter implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "filter_id")
private Integer filterId;

@JoinColumn(name = "user_id", referencedColumnName = "user_id")
@ManyToOne(fetch = FetchType.EAGER)
private SysUser userId;

@Size(max = 45)
@Column(name = "table_name")
private String tableName;

@Size(max = 45)
@Column(name = "column_name")
private String columnName;

@Size(max = 45)
@Column(name = "condition")
private String condition;

@Size(max = 100)
@Column(name = "value")
private String value;


// getters & setters

}

我有专栏名称(例如标题)
我有条件(例如==,!=,> =等) – 我可以将它存储为符号或单词(等于等)
最后我有价值.

问题是“如何为我的服务动态生成谓词?”
表有大约25个字段.

谓词看起来像这样:

public BooleanExpression buildFilteredResult(List<SysFilter> filters) {
    //TODO do it!
    return QTblActivity.tblActivity.title.eq("Value"); 
// I need to do it dynamically for each filter in the list
}

问题是如何通过其字符串值调用columnName.
你有什么建议吗?

最佳答案
将映射过滤条件用于运算符可能更容易

Map<String, Operator> operators = ImmutableMap.of(
  "==", Ops.EQ, "!=", Ops.NE, ">", Ops.GT, "<", Ops.LT,
  ">=", Ops.GOE, "<=", Ops.LOE);

Expressions.predicate(operators.get(condition), 
  stringPath, Expressions.constant(filterValue));

还要确保正确组合谓词

predicates.and(...)

返回一个新谓词并保持谓词不受影响.

也许BooleanBuilder就是你追求的?

转载注明原文:spring – QueryDSL动态谓词 - 代码日志