Repository类的定义:
public interface Repository<T, ID extends Serializable> {
}
T:实体类名
ID:实体类的主键字段数据类型
环境的搭建:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
JpaRepository支持接口规范方法名查询
基于规则写法:
public Employee findByName(String name);
// where name like ?% and age <?
public List<Employee> findByNameStartingWithAndAgeLessThan(String name, Integer age);
// where name like %? and age <?
public List<Employee> findByNameEndingWithAndAgeLessThan(String name, Integer age);
// where name in (?,?....) or age <?
public List<Employee> findByNameInOrAgeLessThan(List<String> names, Integer age);
// where name in (?,?....) and age <?
public List<Employee> findByNameInAndAgeLessThan(List<String> names, Integer age);
对于按照方法命名规则来使用的话,有弊端:
1)方法名会比较长: 约定大于配置
2)对于一些复杂的查询,是很难实现
解决方式:@Query
注解
Query
-
不需要遵循查询方法命名规则
-
支持命名参数和索引参数的使用
使用方式:
查询:@Query("select o from Employee o where id=(select max(id) from Employee t1)") public Employee getEmployeeByMaxId(); @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); @Query("select o from Employee o where o.name like %?1%") public List<Employee> queryLike1(String name); @Query("select o from Employee o where o.name like %:name%") public List<Employee> queryLike2(@Param("name")String name); //开启原始查询,自定义原生sql @Query(nativeQuery = true, value = "select count(1) from employee") public long getCount();
事务的更新与删除:
@Modifying
事务在Spring data中的使用:
@Modifying
@Query("update Employee o set o.age = :age where o.id = :id")
public void update(@Param("id")Integer id, @Param("age")Integer age);
1)事务一般是在Service层
2)@Query、 @Modifying、@Transactional的综合使用
CrudRepository接口
pagingAndSortingRepository
- 接口包含分页与排序功能
- 带排序的查询:findAll( Sort sort )
- 带排序的分页查询:findAll( Pageable pageable )
JpaRepository
JpaSpecificationExecutor
- 封装了JPA Criteria查询条件