Spring Boot+JPA+Mysql--自定义查询

自定义查询可以用于多表的关联查询

数据访问层:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;


public interface BookRepository extends JpaRepository<Book,Long> {

    List<Book> findByAuthor(String author);

    List<Book> findByAuthorAndStatus(String author, int status);

    List<Book> findByDescriptionContains(String des);

//    @Query("select b from Book b where length(b.name) > ?1")
    @Query(value = "select * from book  where LENGTH(name)> ?1", nativeQuery = true)
    List<Book> findByJPQL(int len);


}

service层(业务逻辑层)

@Service
public class BookService {

    @Autowired
    private BookRepository bookRepository;

   /**
     * 自定义查询
     * @param len
     * @return
     */
    public List<Book> findByJPQL(int len) {
        return bookRepository.findByJPQL(len);
   }
 }

web层


@RestController
@RequestMapping("/api/v1")
public class BookApp {

    @Autowired
    private BookService bookService;

    @PostMapping("/books/by")
    public List<Book> findBy(@RequestParam int len) {
//        return bookService.findByAuthor(author);
//        return bookService.findByAuthorAndStatus(author, status);
        //return bookService.findByDescriptionEndsWith(description);

        return bookService.findByJPQL(len);
    }
}
发布了153 篇原创文章 · 获赞 6 · 访问量 2356

猜你喜欢

转载自blog.csdn.net/yangshengwei230612/article/details/103765080