nativeQuery=true 本地查询,就是使用原生的sql语句,直接查询数据表名,而不是实体类对象(根据数据库的不同,在sql的语法或结构方面可能有所区别)进行查询数据库的操作。不设置nativeQuery=true 时,SQL语句中的表名和字段名时实体类名和实体类中的字段名,两种方式作用一样,只是方法不同
@Query(value = "select * from book b where b.name=?1", nativeQuery = true)
List<Book> findByName(String name);
book为数据库中真实存在的数据表,name为book表中的字段。
1. 一个使用@Query注解的简单例子:占位符?1和?2
@Query(value = "select name,author,price from Book b where b.price>?1 and b.price<?2")
List<Book> findByPriceRange(long price1, long price2);
2. Like表达式:指定参数 :name,下面要用@Param("name")指明对应的参数
@Query(value="select * from actor_info where school like '%' :school '%'",nativeQuery = true)
List<Actor> findBySchool(@Param("school")String school);
3. 使用@Param注解注入参数
@Query(value = "select name,author,price from Book b where b.name = :name AND b.author=:author AND b.price=:price") List<Book> findByNamedParam(@Param("name") String name, @Param("author") String author,@Param("price") long price);
4. SPEL表达式( 特别说明:本条可能有误,待验证,不使用#{#entityName},直接使用表名是ok的 )
此处的 '#{#entityName}'值为'Book'对象对应的数据表名称(book)。
实体类Book,使用@Entity注解后,spring会将实体类Book纳入管理。此时默认'#{#entityName}'的值就是'Book'。但是如果使用了@Entity(name = "book")来注解实体类Book,此时'#{#entityName}'的值就变成了'book'。
public interface BookQueryRepositoryExample extends Repository<Book, Long>{
@Query(value = "select * from #{#entityName} b where b.name=?1", nativeQuery = true)
List<Book> findByName(String name);
}