spring data jpa 接口使用

spring data jpa 接口使用

1. 接口继承JpaRepository

public interface CustomerDao extends JpaRepository {}

2. 加Query注解定义方法及返回类型

自定义看得见的sql查询语句,提供的命名方法没有合适的或者比较麻烦的,比如多表查询等

//Jpql语句
@Query(value = " from Customer")
List getAllCustomer();
//分页查询
@Query(value = "from Customer ")
List getAllByPage(Pageable pageable);
//条件查询
@Query(value = "from Customer where custId = ?1 ")
Customer getCustomerById (Long id);
//模糊查询
@Query("from Customer where custAddress like ?1 and custName like ?2")
List getCustomerList (String address, String name);
//更新
@Query("update Customer set custSource = ?1 where custId = ?2")
@Modifying
@Transactional
void updateSource (String source, long id);

spring data jpa 接口使用_第1张图片

3. 按照规定命名创建接口(不用写sql语句,不用写注解)

//id查询
Customer findByCustId (Long id);
//模糊
List findByCustNameLikeAndCustAddressLike(String name,String address);
//分页
Page findByCustAddressLike (String address, Pageable pageable);

接口命名的连接词+entity属性+限制形容词,组成方法名称,然后框架帮我们创建接口的实现方法,只需用@Autowired注入使用即可

spring data jpa 接口使用_第2张图片

Table 3. Supported keywords inside method names
Keyword Sample JPQL 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 ages)

… where x.age in ?1

NotIn

findByAgeNotIn(Collection 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)

你可能感兴趣的:(spring data jpa 接口使用)