JPA 搜索字符串、长整型和布尔型

2023-12-22

我有一个 Spring Boot 应用程序。有一个实体:

@Entity
@Table(name = "user")
public class User {
    private Long id;
    private String name;
    private Long schoolId;
    private Boolean isActive;
    // getters and setters
}

我有一个存储库:

@Repository
public interface UserRepositoryPageable extends PagingAndSortingRepository<User, Long> {
}

我需要提出搜索请求schoolId和过滤器所有领域通过一些字符串。

像这样的事情:

@Query("SELECT u FROM User u " +
        "WHERE u.schoolId = :schoolId AND (" +
        "u.id like %:searchVal% OR " +
        "u.name like %:searchVal% OR " +
        "u.isActive like %:searchVal%)")
Page<User> getUserBySchoolIdWithFilter(@Param("schoolId") Long schoolId,
                                       Pageable pageable,
                                       @Param("searchVal") String searchVal);

但我收到了例外,因为我尝试申请like to Long and Boolean.

例如,如果我尝试按“testSearchValue”进行过滤,我会收到此异常:

java.lang.IllegalArgumentException:参数值 [%testSearchValue%] 与预期类型 [java.lang.Long(不适用)] 不匹配

很遗憾,CAST and CONVERT没有为我工作。

那么有什么解决方法吗?

一些细节

我发送一个GET请求该API:

@RequestMapping(path = "users/{schoolId}/search", method = GET)
public ResponseEntity<Page<User>> searchUserBySchoolWithFilter(
                    @PathVariable(value = "schoolId") Long schoolId, Pageable pageable,
                    @RequestParam(value = "searchVal", required = false) String searchVal) {
    return new ResponseEntity<>(userService
                .getUserBySchoolIdWithFilter(schoolId, pageable, searchVal), HttpStatus.OK);
    }

Then in UserService:

public Page<User> getUserBySchoolIdWithFilter(Long schoolId, Pageable pageable, String searchVal) {
    return userRepositoryPageable.getUserBySchoolIdWithFilter(schoolId, pageable, searchVal);
}

So:

在我看来,这个问题的基本点是代表Long and Boolean as String.
也许更好用nativeQuery?如果是这样,那么你能给我一个关于如何使用的提示吗CAST() or CONVERT() with LIKE clause?


您是否考虑过使用规格 https://docs.spring.io/spring-data/data-jpa/docs/current/api/org/springframework/data/jpa/domain/Specification.html?

使用规范,您可以动态生成WHERESpring 数据查询的一部分。 为了在 Spring Data JPA 查询中使用规范,您必须扩展org.springframework.data.jpa.repository.JpaSpecificationExecutor界面。所以你的用户存储库可能如下所示:

public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
}

您的搜索方法可能如下所示

public List<User> getAllFilterByString(String text) {

    if(StringUtils.isEmpty(text))
        return userRepository.findAll();

    Specification<User> specification =
            (root, query, cb) -> {
                List<Predicate> predicates = new ArrayList<>();
                predicates.add(cb.like(cb.lower(root.get("name")), "%"+text.toLowerCase()+"%"));

                //check if the text value can be casted to long.
                //if it is possible, then add the check to the query
                try {
                    long longValue = Long.valueOf(text);
                    predicates.add(cb.equal(root.get("id"), longValue));
                }
                catch (NumberFormatException e) {
                    //do nothing, the text is not long
                }

                //check if the text can be casted to boolean
                //if it is possible, then add the check to the query

                Boolean value = "true".equalsIgnoreCase(text) ? Boolean.TRUE :
                        "false".equalsIgnoreCase(text) ? Boolean.FALSE : null;

                if(value != null) {
                    predicates.add(cb.equal(root.get("isActive"), value));
                }

                return cb.or(predicates.toArray(new Predicate[] {}));
            };

    return userRepository.findAll(specification);

}

首先我们首先添加name LIKE %text%where 表达式的一部分。

接下来,我们检查该值是否text变量可以转换为long。如果可以,那么我们从字符串中获取 long 值并将其添加到 where 查询中。

最后我们检查是否text变量可以转换为布尔值。如果可以,那么我们也将该检查添加到查询中。

例如,如果值text变量是test1其中部分将是

WHERE name LIKE '%test1%;

如果值text变量是true那么 where 部分将是

WHERE name LIKE '%true%' OR is_active = true;

最后,如果值text变量是12那么 where 部分将是

WHERE name LIKE '%12%' OR id = 12;

Note:我添加了cb.lower(root.get("name")) and text.toLowerCase()到我们按名称搜索时的部分,以使搜索不区分大小写。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JPA 搜索字符串、长整型和布尔型 的相关文章

随机推荐

  • 是否可以在 apache flink CEP 中处理多个流?

    我的问题是 如果我们有两个原始事件流 即Smoke and 温度我们想知道是否有复杂的事件 即Fire通过将运算符应用于原始流已经发生了 我们可以在 Flink 中做到这一点吗 我问这个问题是因为到目前为止我所看到的 Flink CEP 的
  • 当行有子项时复制数据库中的行

    我需要复制表中的行 并复制通过其外键链接到其他表中的所有行 然后复制链接到这些行的所有行 问题是当我复制该行时 密钥将会改变 如何通过表之间的关系传播这些更改 您可以编写一个实现所有复制逻辑的存储过程 本质上 在主表中插入复制行 将新 ID
  • System.IO.DriveInfo 返回错误的磁盘空间值

    更新 这个问题不会出现在我测试过的 Android 设备上 它返回良好的值 非常感谢有关此事的任何指示 我无法从 Mac 台式计算机获取正确的可用空闲空间值 我正在使用 Unity3D C 并使用以下代码 DriveInfo drives
  • 如何为续集更新添加日志记录

    在我的项目中sequelize日志记录已禁用 但我希望在确切的查询中进行主动日志记录 我怎样才能做到这一点 TableModel update counter 0 where id itm i then res gt console log
  • 我可以在同一页面上使用多个版本的 jQuery 吗?

    我正在从事的一个项目需要在客户的网页上使用 jQuery 客户将插入我们将提供的一段代码 其中包括一些
  • 无法在 Meteor 中解码下载的字体

    这是我的CSS font face font family geometria lightlight src url Geometria Light webfont eot src url Geometria Light webfont e
  • PyQt 与 Sqlalchemy 集成

    我正在尝试通过 Sqlalchemy 将使用 PyQt 创建的表单添加到数据库中 但我猜我的代码有问题 我收到此错误 le Users tunji Desktop employee py line 57 in AddEmployee ses
  • java中简单的“检查更新”库

    我正在使用 Eclipse RCP 但是 主要是因为我完全控制了 UI 删除了所有贡献 从头开始进行首选项等 我只是无法接受所包含的更新管理器的复杂性和需求 另外 我不使用插件功能 并且应用程序插件必须被提取 尽管我可以解决最后一个问题 不
  • 如何在 Laravel REST API 中使用 PUT 方法更新图像?

    我正在尝试使用 Laravel 构建一个 REST API 用户需要在其中更新他们的图像 但是 如果我在邮递员中使用 PUT 方法 它不会更新图像或将图像存储在指定文件夹中 如果我使用 POST 它会更新图像并保存在文件夹中 但它不会将文件
  • 更改日期格式化程序的区域设置

    我在我的应用程序中使用日期格式化程序来显示一些日期 但我希望该日期以阿拉伯语显示 所以我尝试更改格式化程序的区域设置 如下所示 var now new DateTime now var formatter DateFormat yMMMd
  • 如何使用 Asp.Net Core 实现基于权限的访问控制

    我正在尝试使用 aspnet core 实现基于权限的访问控制 为了动态管理用户角色和权限 create product delete product 等 它们存储在数据库中 数据模型就像https i stack imgur com CH
  • 如何加载外部文件并确保它首先在 JSFiddle 中运行?

    我有一个 JsFiddlehere http jsfiddle net deeptechtons rEzW5 2 并添加了通过外部 JS 资源部分加载的 Microsoft AJAX 如何判断 AJAX 文件加载完成后我的 JS 代码是否运
  • 单页应用程序 SEO 和无限滚动 AngularJS

    我们有一个网站 其提要类似于 pinterest 并计划将 jquery soup 重构为更结构化的内容 最有可能的两个候选者是 AngularJS 和 Backbone Marionette 该网站是用户生成的 主要以消费为导向 典型的
  • Symfony 表单字段属性empty_data 被忽略

    根据Symfony 2 4 文档 http symfony com doc current reference forms types text html empty data 任何不需要但提交时没有任何值的表单字段 选择字段的默认值或文本
  • Django 自定义用户模型密码未经过哈希处理

    我有自己的自定义用户模型 也有自己的管理器 models class MyUser AbstractBaseUser PermissionsMixin email models EmailField max length 255 uniqu
  • 仅将视口设置为横向模式

    我正在完成我的网站 除了一件小事之外 一切都运行良好 当我使用 iPhone 时 纵向模式完全符合我的要求 问题在于横向模式 我就像我已经设计了它 但我不喜欢最终版本 所以我需要插入另一行代码 但我不知道该怎么做 这就是我现在拥有的 现在我
  • 如何防止解析JSON时去掉小数点?

    如果你这样做 var parsed JSON parse myNum 0 0 然后当你看parsed myNum 你就得到了0 很公平 如果你这样做parsed myNum toString 你得到 0 基本上 我正在寻找一种方法将其转换为
  • 通过ReactJs代码运行shell命令

    我有一个文件存储在本地计算机中 并且也连接了一台打印机 因此 通常如果我想将文件打印到连接的打印机 我会在命令提示符中运行以下命令 cd
  • xCode - UIVisualEffectView 动画

    我在制作 VisualEffetView 动画时遇到问题 这是我声明它的代码 UIBlurEffect blur UIBlurEffect effectWithStyle UIBlurEffectStyleLight effectView
  • JPA 搜索字符串、长整型和布尔型

    我有一个 Spring Boot 应用程序 有一个实体 Entity Table name user public class User private Long id private String name private Long sc