spring Data JPA 高级用法

455 阅读1分钟

这是我参与11月更文挑战的第7天,活动详情查看:2021最后一次更文挑战

不用写sql的

实例

Person findByName(String name);

JPQL定义的方法命名的一些范式

key范式sql语句
AndfindByLastnameAndFirstnamewhere x.lastname = ?1 andx.firstname = ?2
OrfindByLastnameOrFirstnamewhere x.lastname = ?1 or x.firstname = ?2
Is,EqualsfindByFirstnameIs,,findByFirstnameEqualswhere x.firstname = ?1
BetweenfindByStartDateBetweenwhere x.startDate between ?1 and ?2
LessThanfindByAgeLessThanwhere x.age < ?1
LessThanEqualfindByAgeLessThanEqualwhere x.age ⇐ ?1
GreaterThanfindByAgeGreaterThanwhere x.age > ?1
GreaterThanEqualfindByAgeGreaterThanEqualwhere x.age >= ?1
AfterfindByStartDateAfterwhere x.startDate > ?1
BeforefindByStartDateBeforewhere x.startDate < ?1
IsNullfindByAgeIsNullwhere x.age is null
IsNotNull,NotNullfindByAge(Is)NotNullwhere x.age not null
LikefindByFirstnameLikewhere x.firstname like ?1
NotLikefindByFirstnameNotLikewhere x.firstname not like ?1
StartingWithfindByFirstnameStartingWithwhere x.firstname like ?1 (parameter bound with appended %)
EndingWithfindByFirstnameEndingWithwhere x.firstname like ?1 (parameter bound with prepended %)
ContainingfindByFirstnameContainingwhere x.firstname like ?1 (parameter bound wrapped in %)
OrderByfindByAgeOrderByLastnameDescwhere x.age = ?1 order by x.lastname desc
NotfindByLastnameNotwhere x.lastname <> ?1
InfindByAgeIn(Collection ageswhere x.age in ?1
NotInfindByAgeNotIn(Collection agewhere x.age not in ?1
TRUEfindByActiveTruewhere x.active = true
FALSEfindByActiveFalse()where x.active = false
IgnoreCasefindByFirstnameIgnoreCasewhere 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);