1.Spring Data JPA提供的查询方法已经可以解决大部分的应用场景,但是对于某些业务来说,我们还需要灵活的构造查询条件,这时就可以使用@Query注解,结合JPQL的语句方式完成查询
JPQL
/**
* 使用 jqpl通过用户名查询数据
* jqpl:from Customer where custName=?
*
*/
@Query(value = "from Customer where custName=?")
public Customer findJpql(String custName);
/**
* jqpl:from Customer where custName=? and custId=?
* 多占位符操作
* custName=?1 取第一个参数
* custId=?2 取第二个参数
*/
@Query("from Customer where custName=?1 and custId=?2")
public Customer findCustNameAndCustId(String name, long id);
/**
* jpql 完成更新
* jpql:update Customer set custName=? where custId=?;
*
* @modifying *当前是一个更新操作
*/
@Query("update Customer set custName=? where custId=?")
@Modifying
@Transactional
public void updateCustomer(String name, long id);
SQL
/**
* 使用sql形式查询
* 查询全部客户
* sql:select * from cst_customer
*
* nativeQuery :false jpql查询 默认
* true sql查询
*/
@Query(value ="select * from cst_customer",nativeQuery = true)
public List<Object[]> findSql();
/**
* sql模糊查询
* @return
*/
@Query(value ="SELECT * FROM cst_customer WHERE cust_name LIKE ?",nativeQuery = true)
public List<Object[]> likeSql(String name);
方法命名规则查询
/**
* 约定:
* 1 *findBy:查询
* 对象中的属性名(首字母大写)。查询的条件
* findByCustName --- 就是更具客户名称精准查询
* 会进行方法名的解析
sql:select * from cst_customer where cust_name =?;
*
* 2 *findBy + 属性名称
* *findBy + 属性名称 +查询方式(like|isnull)
* findByCustNameLike
* 3 *findBy + 属性名称 +查询方式(like|isnull)+多条件连接符(and|or)+属性名+查询方式
*/
public Customer findByCustName(String custName);
//模糊查询 Like
public List<Customer> findByCustNameLike(String custName);
//根据用户名模糊查询 和 所属行业精准查询
public List<Customer> findByCustNameLikeAndCustIndustry(String custName,String custIndustry);