gpt4 book ai didi

Java,CriteriaBuilder,带有可选参数的查询 "where"

转载 作者:行者123 更新时间:2023-12-02 01:10:18 25 4
gpt4 key购买 nike

我必须重写一些代码,但在互联网上找不到正确的信息。原始部分如下所示:

String query = "select * from sublog_type_map_v where 1 = 1";
if (responsibleGroupId != null && responsibleGroupId.length() != 0 && !responsibleGroupId.equals("0")) {
query += " and responsible_group_id = " + responsibleGroupId;
}
if (categoryId != null && categoryId.length() != 0 && !categoryId.equals("0")) {
query += " and category_id = " + categoryId;
}
if (typeId != null && typeId.length() != 0 && !typeId.equals("0")) {
query += " and type_id = " + typeId;
}
if (subtypeId != null && subtypeId.length() != 0 && !subtypeId.equals("0")) {
query += " and subtype_id = " + subtypeId;
}

我已经继续执行此代码:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<SublogTypeMapV> query = builder.createQuery(SublogTypeMapV.class);
Root<SublogTypeMapV> root = query.from(SublogTypeMapV.class);
query.select(root).where(builder.equal(root.get("responsibleGroupId"), responsibleGroupId));

但是这个“where”应该被认为是可选的,使用“if”表达式,以及其他三个参数(我将在稍后添加)。我不知道该怎么做,有人可以帮助我吗?

最佳答案

我想这可以满足需要 -

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<SublogTypeMapV> query = builder.createQuery(SublogTypeMapV.class);
Root<SublogTypeMapV> root = query.from(SublogTypeMapV.class);
query = query.select(root);
if("some boolean expression") {
query = query.where(builder.equal(root.get("responsibleGroupId"), responsibleGroupId));
}

类似地,您可以处理内部的其他条件。

关于Java,CriteriaBuilder,带有可选参数的查询 "where",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59497279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com