简体   繁体   中英

How to create query with Spring Data JPA?

Please help me. I can not create query from native sql using spring data. How do I convert the following expression?

select distinct brand, model from cars 
where brand like '%:query%' or model like '%:query%' limit 2;

You could use projections with Spring Data JPA, something of the likes of:

interface SimpleCar {
    String getBrand();
    String getModel();
}

and then:

List<SimpleCar> findDistinctByBrandLikeOrModelLike(String query);

You can review here for different options to query a DB with some examples.

By the way, if you want to see what queries your methods are executing you can activate DEBUG logging mode in log4j for org.springframework package or org.hibernate (if you're using Hibernate)

Use:

@Query("select distinct brand, model from cars " +
       "where brand like %:query% or model like %:query% limit 2")
public List<Car> find(@Param("query") String query);

Basically what you had but without the speech marks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM