SpringBoot 使用JPA+MySQL+Thymeleaf 总结 二
方法一
使用原生sql查询 或者 为方法名增加 Pageable参数
import org.springframework.data.domain.Pageable;
public interface BookQueryRepository extends Repository<Book, Long> {
//原生的sql语句,要使用数据表名
@Query(value = "select * from tb_book b where b.name=?1", nativeQuery = true)
List<Book> findByName(String name);
//基础查询 重要说明 JPA规范中的定义JPQL是不能使用星号(*)来查询的
@Query(value = "select name,author,price from Book b where b.price>?1 and b.price<?2")
List<Book> findByPriceRange(long price1, long price2);
@Query("select t from Book t")
List<Book> findAllBook1();
@Query("select * from book " , nativeQuery = true)
List<Book> findAllBook2();
//Like表达式 @Query(value = "select name,author,price from Book b where b.name like %:name%") List<Book> findByNameMatch(@Param("name") String name); //使用@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); //分页查询 原生sql语句 @Query(value = "SELECT * FROM tb_book WHERE name = ?1", countQuery = "SELECT count(*) FROM tb_book WHERE name = ?1", nativeQuery = true) Page<Book> findByName(String name, Pageable pageable); //分页查询 @Query("select name,author,price from Book b where b.name=?") public List<Book> findByNamePaged(String certNum,Pageable pageable); }
业务层调用
public class BookService { @Autowired private BookQueryRepository bookQueryDao; public Page<Book> getBook(int pageNumber,int pageSize){ PageRequest request = this.buildPageRequest(pageNumber,pageSize); Page<Book> result= bookQueryDao.findByName("123123",request); return result; } //构建PageRequest private PageRequest buildPageRequest(int pageNumber, int pagzSize) { return new PageRequest(pageNumber - 1, pagzSize, null); } }
方法二
直接使用 PagingAndSortingRepository
import org.springframework.data.repository.PagingAndSortingRepository; public interface BookQueryRepository extends PagingAndSortingRepository<Book, String> { }
业务层调用
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; public class BookService { @Autowired private BookQueryRepository bookQueryDao; public Page<Book> getBook(int pageNumber,int pageSize){ PageRequest request = this.buildPageRequest(pageNumber,pageSize); Page<Book> result= bookQueryDao.findAll(request); return result; } //构建PageRequest private PageRequest buildPageRequest(int pageNumber, int pagzSize) { return new PageRequest(pageNumber - 1, pagzSize, null); } }