jpa命名規則 jpa使用sql語句 @Query

關鍵字
方法命名
sql where字句sql

And
findByNameAndPwd
where name= ? and pwd =?.net

Or
findByNameOrSex
where name= ? or sex=?blog

Is,Equals
findById,findByIdEquals
where id= ?事務

Between
findByIdBetween
where id between ? and ?it

LessThan
findByIdLessThan
where id < ?io

LessThanEquals
findByIdLessThanEquals
where id <= ?date

GreaterThan
findByIdGreaterThan
where id > ?List

GreaterThanEquals
findByIdGreaterThanEquals
where id > = ?select

After
findByIdAfter
where id > ?service

Before
findByIdBefore
where id < ?

IsNull
findByNameIsNull
where name is null

isNotNull,NotNull
findByNameNotNull
where name is not null

Like
findByNameLike
where name like ?

NotLike
findByNameNotLike
where name not like ?

StartingWith

findByNameStartingWith
where name like '?%'

EndingWith
findByNameEndingWith
where name like '%?'

Containing
findByNameContaining
where name like '%?%'

OrderBy
findByIdOrderByXDesc
where id=? order by x desc

Not
findByNameNot
where name <> ?

In
findByIdIn(Collection<?> c)
where id in (?)

NotIn
findByIdNotIn(Collection<?> c)
where id not  in (?)

True

findByAaaTue

where aaa = true

False
findByAaaFalse
where aaa = false

IgnoreCase
findByNameIgnoreCase
where UPPER(name)=UPPER(?)

//where name in(?,?...) and age<?
public List<Employee> findByNameInAndAgeLessThan(List<String> names,Integer age);

在方法上加@Query就不須要遵照上面的規則了,能夠進行自定義sql。

有兩種方式傳參:

@Query("select o from Employee o where o.name=?1 and o.age=?2")
public List<Employee> queryParams1(String name,Integer age);
@Query("select o from Employee o where o.name=:name and o.age=:age")
public List<Employee> queryParams2(@Param("name") String name, @Param("age") Integer age);

修改數據的時候須要使用到三個註解

@Modifying
@Query("update Employee o set o.age=:age where o.id=:id")
public void update(@Param("id") Integer id,@Param("age") Integer age);
首先是query這裏須要加上@Modifying

可是僅僅加上這個會報錯,須要打開事務

因此還須要在service層方法上開啓事務,(service層開啓事務,事務會做用於整個查詢部分的方法)

@Transactional
public void update(Integer id,Integer age){
    employeeRepository.update(id,age);
}
相關文章
相關標籤/搜索