Get query from file in SPRING BOOT using @Query

后端 未结 3 961
借酒劲吻你
借酒劲吻你 2021-01-25 03:11

I have a proyect that use to load queries this:

@Query(value = SELECT_BY_USER_ID, nativeQuery = true)
Employee findByUserId(@Param(\"userId\") String userId);


        
相关标签:
3条回答
  • 2021-01-25 03:37

    If you need to load SQL from resources folder, you can try spring-data-sqlfile library. It supports loading SQL queries from resources. So you just need to put your SQL queries to the resources folder and than you can reference them in SqlFromResource annotation:

    @Repository
    public interface UserRepository extends JpaRepository<User, Integer> {
        @SqlFromResource(path = "select_user_by_id.sql")
        User findById(int userId);
    }
    

    The output will be like:

    @Repository
    public interface UserRepositoryGenerated extends JpaRepository<User, Integer> {    
      @Query(
          value = "SELECT *     FROM users     WHERE id = :userId",
          nativeQuery = true
      )
      User findById(int userId);
    }
    
    0 讨论(0)
  • 2021-01-25 03:50

    Unfortunately, spring data doesn't seem to support direct properties reference withing @Query anno (like in @Value). Despite that and assuming you use spring-data-jpa and Hibernate it is possible to use an external .xml file to store your queries as named queries and refer to them by method name, or like

    @Query(nativeQuery = true, name="Repository1.query1")
    

    This is a nice article on this matter : JPA Queries in XML File and it describes how to place your .xml file elsewhere than the expected orm.xml

    0 讨论(0)
  • 2021-01-25 03:51

    Configured queries cannot be loaded from YML, as far as I know. They can be loaded from another file. Create a file in your resource project folder named /META-INF/jpa-named-queries.properties and then place your query:

    Employee.findById=select * from Employee e where e.id=?1
    

    and then call your query:

    @Query(name = "Employee.findById")
    Employee findByUserId(String id);
    
    0 讨论(0)
提交回复
热议问题