【问题标题】:How can I use my parameter in query annotation in Spring Boot?如何在 Spring Boot 的查询注释中使用我的参数?
【发布时间】:2021-12-27 23:49:56
【问题描述】:

我创建了一个字符串形式的 MySQL 查询。我想将它添加到我的 @Query 注释中。我无法从我的函数中获取参数。我在存储库findAllFaces 函数@Query 中尝试了:query,但它不起作用。

【问题讨论】:

    标签: java mysql spring-boot annotations


    【解决方案1】:

    使用?0?1?{index of parameter}.... 试试这个:

    @Query(value = "SELECT f.id FROM faces f WHERE ?0", nativeQuery = true)
    List<String> findAllFaces(String query);
    

    另一个例子:

    @Query(value = "SELECT * FROM faces WHERE key1 = ?0 AND key2 = ?1 AND key3 = ?2", nativeQuery = true)
    List<String> findByKey1AndKey2AndKey3(String value1, String value2, String value3);
    

    【讨论】:

      【解决方案2】:

      解决方案 1:

      public interface UserRepository extends JpaRepository<User, Long> {
      
        @Query("select u from User u where u.emailAddress = ?1")
        User findByEmailAddress(String emailAddress);
      }
      

      https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query

      解决方案 2:

      @Entity
      @NamedQuery(name = "User.findByEmailAddress",
        query = "select u from User u where u.emailAddress = ?1")
      public class User {
      
      }
      

      参考文档:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.named-queries.annotation-based-configuration

      【讨论】:

        猜你喜欢
        • 2020-10-21
        • 1970-01-01
        • 2020-05-22
        • 2019-10-16
        • 2016-09-04
        • 2020-03-03
        • 2020-05-31
        • 2021-09-26
        • 2019-02-22
        相关资源
        最近更新 更多