简体   繁体   中英

Spring JPA long SQL String for NativeQuery

In my Spring JPA Project, I have a repo file as such:

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

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

With this, I can still copy paste the SQL and run in my DB software.

But when it comes to large queries as such:

    @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
        );

I can't really directly copy paste and run in the DB software, I have to remove the "+" "\n" characters. I've tried Java's """SQL_QUERY_STRING""" but it doesn't allow it.

Are there any alternative approach to this?

UPDATE

I tried the triple double-quote but it gives:

String literal is not properly closed by a double-quote

在此处输入图像描述

JEP 355 introduces multiline strings. You can leverage them to simply copy-paste the sql:

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

Note, that it was introduced in java 13 as a preview. So you need to upgrade at least to java 13 and enable preview features to make use of it.

If not, you can improve readability by replacing newline characters with spaces:

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

I've tried @Andronicus's method, but it doesn't work out for me.

The way I solved it is by creating a new directory and file:
/src/main/resources/META-INF/orm.xml

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings version="2.0" xmlns="http://java.sun.com/xml/ns/persistence/orm"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
    http://java.sun.com/xml/ns/persistence/orm_2_0.xsd ">

<named-native-query name="Student.findStudents" result- 
class="path/package_to_student_class">
    <query>
        SELECT
        *
        FROM
        student
        WHERE
        (
        `id` LIKE CONCAT('%', :keyword, '%') OR
        `name` LIKE CONCAT('%', :keyword, '%') OR
        `desc` LIKE CONCAT('%', :keyword, '%') OR
        `sex` LIKE CONCAT('%', :keyword, '%') OR
        )
    </query>
</named-native-query>
</entity-mappings>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM