Spring Boot + JPA + Mysql-- custom queries

 

Custom queries can be used to associate a multi-table query

 

 

Data Access Layer:

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 layer (business logic)

@Service
public class BookService {

    @Autowired
    private BookRepository bookRepository;

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

web layer


@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);
    }
}

 

Published 153 original articles · won praise 6 · views 2356

Guess you like

Origin blog.csdn.net/yangshengwei230612/article/details/103765080