首页 > 解决方案 > 用于 NativeQuery 的 Spring JPA 长 SQL 字符串

问题描述

在我的 Spring JPA 项目中,我有一个这样的 repo 文件:

@Repository
public interface StudentRepository extends JpaRepository<Student, Integer>{

@Query(value = "select * from students", nativeQuery = true)
public List<Student> findStudents(
        @Param("keyword") String keyword
        );
}

有了这个,我仍然可以复制粘贴 SQL 并在我的数据库软件中运行。

但是当涉及到大型查询时:

    @Query(value = "SELECT\n" + 
        "*\n" + 
        "FROM\n" + 
        "students\n" + 
        "WHERE\n" + 
        "(\n" + 
        "`id` LIKE CONCAT('%', :keyword, '%') OR\n" + 
        "`name` LIKE  CONCAT('%', :keyword, '%') OR\n" + 
        "`desc` LIKE  CONCAT('%', :keyword, '%') OR\n" + 
        "`sex` LIKE  CONCAT('%', :keyword, '%')\n" + 
        ")", nativeQuery = true)
public List<Student> findStudents(
        @Param("keyword") String keyword
        );

我不能真正直接复制粘贴并在DB软件中运行,我必须删除“+”“\n”字符。我已经尝试过 Java 的 """SQL_QUERY_STRING""" 但它不允许这样做。

有没有其他方法可以解决这个问题?

更新

我尝试了三重双引号,但它给出了:

双引号未正确关闭字符串文字

在此处输入图像描述

标签: javaspringspring-bootjava-8jpql

解决方案


JEP 355引入了多行字符串。您可以利用它们简单地复制粘贴 sql:

@Query(value = 
"""
    select * 
    from students
    ...
""", nativeQuery = true)

请注意,它是在 java 13 中作为预览引入的。因此,您至少需要升级到 java 13 并启用预览功能才能使用它。

如果没有,您可以通过用空格替换换行符来提高可读性:

@Query(value = "SELECT " + 
    "FROM " + 
    "students " + 
    ...

推荐阅读