这是我参与11月更文挑战的第7天,活动详情查看:2021最后一次更文挑战
不用写sql的
实例
Person findByName(String name);
JPQL定义的方法命名的一些范式
| key | 范式 | sql语句 |
|---|---|---|
| And | findByLastnameAndFirstname | where x.lastname = ?1 andx.firstname = ?2 |
| Or | findByLastnameOrFirstname | where x.lastname = ?1 or x.firstname = ?2 |
| Is,Equals | findByFirstnameIs,,findByFirstnameEquals | where x.firstname = ?1 |
| Between | findByStartDateBetween | where x.startDate between ?1 and ?2 |
| LessThan | findByAgeLessThan | where x.age < ?1 |
| LessThanEqual | findByAgeLessThanEqual | where x.age ⇐ ?1 |
| GreaterThan | findByAgeGreaterThan | where x.age > ?1 |
| GreaterThanEqual | findByAgeGreaterThanEqual | where x.age >= ?1 |
| After | findByStartDateAfter | where x.startDate > ?1 |
| Before | findByStartDateBefore | where x.startDate < ?1 |
| IsNull | findByAgeIsNull | where x.age is null |
| IsNotNull,NotNull | findByAge(Is)NotNull | where x.age not null |
| Like | findByFirstnameLike | where x.firstname like ?1 |
| NotLike | findByFirstnameNotLike | where x.firstname not like ?1 |
| StartingWith | findByFirstnameStartingWith | where x.firstname like ?1 (parameter bound with appended %) |
| EndingWith | findByFirstnameEndingWith | where x.firstname like ?1 (parameter bound with prepended %) |
| Containing | findByFirstnameContaining | where x.firstname like ?1 (parameter bound wrapped in %) |
| OrderBy | findByAgeOrderByLastnameDesc | where x.age = ?1 order by x.lastname desc |
| Not | findByLastnameNot | where x.lastname <> ?1 |
| In | findByAgeIn(Collection ages | where x.age in ?1 |
| NotIn | findByAgeNotIn(Collection age | where x.age not in ?1 |
| TRUE | findByActiveTrue | where x.active = true |
| FALSE | findByActiveFalse() | where x.active = false |
| IgnoreCase | findByFirstnameIgnoreCase | where UPPER(x.firstame) = UPPER(?1) |
可以自己写SQL
// @Query有nativeQuery=true,表示可执行的原生sql,原生sql指可以直接复制sql语句给参数赋值就能运行
@Query(value = "select * from person where name = ?1",nativeQuery = true)
Person findPersonByName(String Name);
//@Query无nativeQuery=true, 表示不是原生sql,查询语句中的表名则是对应的项目中实体类的类名
@Query(value = "select p from person p where p.uname = :name")
Person findPersonByNameTwo(@Param("name") String name);
//对于自定义sql的删改方法,在方法上还要添加`@Transactional/@Modifying`注解
@Transactional
@Modifying
@Query(value = "delete from Account where id =?1",nativeQuery = true)
void delAccount(int id);