动态SQL-Spring Data Jpa

来源:互联网 发布:上海东方网络金融好吗 编辑:程序博客网 时间:2024/06/14 05:23

官方文档很有用,不会的直接Ctrl-F

一.注意事项

  根据关键词,jpa可以构造许多SQL,满足基本需要。但是一些诸如更新的SQL,仍需要使用@Query动态构造。动态构造SQL时有几个对于新手来说很坑的地方需要注意下,也算是jpa的基本常识。
  

  1. @Query里边的内容表名字段名都需要替换成对应实体列的类名变量名。由于思维一直停留在mybatis,笔者在这里浪费了一些时间;
  2. 更新操作和删除操作需要加@Transactional@Modifying两个注解;
  3. 不等号使用<>

二.其他符号

  除此之外jpa还还有 @Param、=: 等符号。详情参见官方文档

三.示例代码

//表格invoke_count加1    @Modifying    @Transactional    @Query("update RequestUrlMapper r set r.invokeCount=r.invokeCount+1 where r.status <>'SUCCESS' and r.deleteFlag=0")    void invokeCountCreate();

四.关键字及动态SQL示例说明

Table 4. Supported keywords inside method namesKeywordSampleJPQL snippet

And

findByLastnameAndFirstname

… where x.lastname = ?1 and x.firstname = ?2

Or

findByLastnameOrFirstname

… where x.lastname = ?1 or x.firstname = ?2

Is,Equals

findByFirstname,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<Age> ages)

… where x.age in ?1

NotIn

findByAgeNotIn(Collection<Age> ages)

… 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)

原创粉丝点击