首页 > 技术文章 > Spring Data JPA

kkxwze 2021-04-26 22:54 原文

本套课程所涉及的技术:
Hibernate
JPA标准
Hibernate JPA
Spring Data
Spring Data JPA
Spring Data Redis

 

 

 

 

 

 

SpringData 第三章 Spring Data JPA(重点)

Spring Data JPA:Spring Data JPA 是 spring data 项目下的一个模块。提供了一套基于 JPA 标准操作数据库的简化方案。底层默认的是依赖 Hibernate JPA 来实现的。 Spring Data JPA 的技术特点:我们只需要定义接口并集成 Spring Data JPA 中所提供的接 口就可以了。不需要编写接口实现类。

一、 创建 Spring Data JPA 项目

 1 导入 jar

      

 

 

 2 修改配置文

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 配置读取 properties 文件的工具类 -->
<context:property-placeholder
location="classpath:jdbc.properties"/><!-- 配置 c3p0 数据库连接池 -->
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="driverClass" value="${jdbc.driver.class}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- Spring 整合 JPA 配置 EntityManagerFactory-->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBe
an">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- hibernate 相关的属性的注入 -->
<!-- 配置数据库类型 -->
<property name="database" value="MYSQL"/>
<!-- 正向工程 自动创建表 -->
<property name="generateDdl" value="true"/>
<!-- 显示执行的 SQL -->
<property name="showSql" value="true"/>
</bean>
</property>
<!-- 扫描实体的包 -->
<property name="packagesToScan">
<list>
<value>com.bjsxt.pojo</value>
</list>
</property>
</bean>
<!-- 配置 Hibernate 的事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory"
ref="entityManagerFactory"/>
</bean>
<!-- 配置开启注解事务处理 -->
<tx:annotation-driven transaction-manager="transactionManager"/><!-- 配置 springIOC 的注解扫描 -->
<context:component-scan base-package="com.bjsxt"/>
<!-- Spring Data JPA 的配置 -->
<!-- base-package:扫描 dao 接口所在的包 -->
<jpa:repositories base-package="com.bjsxt.dao"/>
</beans>

3 编写 Dao

public interface UsersDao extends JpaRepository<Users, Integer> { //第一个参数对象,第二个参数主键类型
}

4 编写测试代

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class UsersDaoImplTest {
@Autowired
private UsersDao usersDao;
/**
* 添加用户
*/
@Test
@Transactional// 在测试类对于事务提交方式默认的是回滚。
@Rollback(false)//取消自动回滚
public void testInsertUsers(){
Users users = new Users();
users.setUserage(24);
users.setUsername("张三");
this.usersDao.save(users);
}
}

二、 Spring Data JPA 的接口继承结

 

三、 Spring Data JPA 的运行

@PersistenceContext(name="entityManagerFactory")
private EntityManager em;
@Test
public void test1(){
//org.springframework.data.jpa.repository.support.SimpleJpaRepositor
y@fba8bf
//System.out.println(this.usersDao);
//class com.sun.proxy.$Proxy29 代理对象 是基于 JDK 的动态代理方式
创建的
//System.out.println(this.usersDao.getClass());
JpaRepositoryFactory factory = new JpaRepositoryFactory(em);
//getRepository(UsersDao.class);可以帮助我们为接口生成实现类。而
这个实现类是 SimpleJpaRepository 的对象
//要求:该接口必须要是继承 Repository 接口
UsersDao ud = factory.getRepository(UsersDao.class);
System.out.println(ud);
System.out.println(ud.getClass());
}

四、 Repository 接口

Repository 接口是 Spring Data JPA 中为我我们提供的所有接口中的顶层接口

Repository 提供了两种查询方式的支持

1)基于方法名称命名规则查询

2)基于@Query 注解查询

1 方法名称命名规则查询        规则:findBy(关键字)+属性名称(属性名称的首字母大写)+查询条件(首字母大写)

 

1.1创建接口

/**
* Repository 接口讲解
* @author Administrator
*
*/
public interface UsersDao extends Repository<Users, Integer> {
List<Users> findByUsernameIs(String string);List<Users> findByUsernameLike(String string);
List<Users> findByUsernameAndUserageGreaterThanEqual(String
name,Integer age);
}

1.2测试类

/**
* Repository 接口测试
* @author Administrator
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RepositoryTest {
@Autowired
private UsersDao usersDao;
/**
* 需求:使用用户名作为查询条件
*/
@Test
public void test1(){
/**
* 判断相等的条件,有三种表示方式
* 1,什么都不写,默认的就是做相等判断
* 2,Is
* 3,Equal
*/
List<Users> list = this.usersDao.findByUsernameIs("王五");
for (Users users : list) {
System.out.println(users);
}
}
/**
* 需求:根据用户姓名做 Like 处理
* Like:条件关键字
*/
@Test
public void test2(){List<Users> list = this.usersDao.findByUsernameLike("王%");
for (Users users : list) {
System.out.println(users);
}
}
/**
* 需求:查询名称为王五,并且他的年龄大于等于 22 岁
*/
@Test
public void test3(){
List<Users> list =
this.usersDao.findByUsernameAndUserageGreaterThanEqual("王五", 22);
for (Users users : list) {
System.out.println(users);
}
}
}

2 基于@Query 注解的查询

  2.1通过 JPQL 语句查询

    JPQL:通过 Hibernate 的 HQL 演变过来的。他和 HQL 语法及其相似。

   2.1.1创建接口

  

/**
* Repository 接口讲解
* @author Administrator
*
*/
public interface UsersDao extends Repository<Users, Integer> {
//方法名称命名规则
List<Users> findByUsernameIs(String string);
List<Users> findByUsernameLike(String string);
List<Users> findByUsernameAndUserageGreaterThanEqual(String
name,Integer age);
//使用@Query 注解查询
@Query(value="from Users where username = ?")
List<Users> queryUserByNameUseJPQL(String name);@Query("from Users where username like ?")
List<Users> queryUserByLikeNameUseJPQL(String name);
@Query("from Users where username = ? and userage >= ?")
List<Users> queryUserByNameAndAge(String name,Integer age);
}

2.1.2测试类

/**
* 测试@Query 查询 JPQL
*/
@Test
public void test4(){
List<Users> list = this.usersDao.queryUserByNameUseJPQL("王五
");
for (Users users : list) {
System.out.println(users);
}
}
/**
* 测试@Query 查询 JPQL
*/
@Test
public void test5(){
List<Users> list = this.usersDao.queryUserByLikeNameUseJPQL(" 王%");
for (Users users : list) {
System.out.println(users);
}
}
/**
* 测试@Query 查询 JPQL
*/
@Test
public void test6(){
List<Users> list = this.usersDao.queryUserByNameAndAge("王五",
22);
for (Users users : list) {System.out.println(users);
}
}

2.2通过 SQL 语句查询

  2.2.1创建接口

/**
* Repository 接口讲解
* @author Administrator
*
*/
public interface UsersDao extends Repository<Users, Integer> {
//方法名称命名规则
List<Users> findByUsernameIs(String string);
List<Users> findByUsernameLike(String string);
List<Users> findByUsernameAndUserageGreaterThanEqual(String
name,Integer age);
//使用@Query 注解查询
@Query(value="from Users where username = ?")
List<Users> queryUserByNameUseJPQL(String name);
@Query("from Users where username like ?")
List<Users> queryUserByLikeNameUseJPQL(String name);
@Query("from Users where username = ? and userage >= ?")
List<Users> queryUserByNameAndAge(String name,Integer age);
//使用@Query 注解查询 SQL
//nativeQuery:默认的是 false.表示不开启 sql 查询。是否对 value 中的语句
做转义。
@Query(value="select * from t_users where username
= ?",nativeQuery=true)
List<Users> queryUserByNameUseSQL(String name);
@Query(value="select * from t_users where username
like ?",nativeQuery=true)
List<Users> queryUserByLikeNameUseSQL(String name);
@Query(value="select * from t_users where username = ? and
userage >= ?",nativeQuery=true)List<Users> queryUserByNameAndAgeUseSQL(String name,Integer age);
}

2.2.2测试类

/**
* 测试@Query 查询 SQL
*/
@Test
public void test7(){
List<Users> list = this.usersDao.queryUserByNameUseSQL("王五");
for (Users users : list) {
System.out.println(users);
}
}
/**
* 测试@Query 查询 SQL
*/
@Test
public void test8(){
List<Users> list = this.usersDao.queryUserByLikeNameUseSQL(" 王%");
for (Users users : list) {
System.out.println(users);
}
}
/**
* 测试@Query 查询 SQL
*/
@Test
public void test9(){
List<Users> list = this.usersDao.queryUserByNameAndAgeUseSQL(" 王五", 22);
for (Users users : list) {
System.out.println(users);
}
}

3 通过@Query 注解完成数据更新

  3.1创建接口

@Query("update Users set userage = ? where userid = ?")
@Modifying //@Modifying 当前语句是一个更新语句
void updateUserAgeById(Integer age,Integer id);

3.2测试

/**
* 测试@Query update
*/
@Test
@Transactional
@Rollback(false)
public void test10(){
this.usersDao.updateUserAgeById(24, 5);
}

五、 CrudRepository 接口

1 创建接口

/**
* CrudRepository 接口讲解
* @author Administrator
*
*/
public interface UsersDao extends CrudRepository<Users, Integer> {
}

2 测试代

/**
* CrudRepository 接口测试
* @author Administrator
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")public class RepositoryTest {
@Autowired
private UsersDao usersDao;
/**
* 添加单条数据
*/
@Test
public void test1(){
Users user = new Users();
user.setUserage(21);
user.setUsername("赵小丽");
this.usersDao.save(user);
}
/**
* 批量添加数据
*/
@Test
public void test2(){
Users user = new Users();
user.setUserage(21);
user.setUsername("赵小丽");
Users user1 = new Users();
user1.setUserage(25);
user1.setUsername("王小虎");
List<Users> list= new ArrayList<>();
list.add(user);
list.add(user1);
this.usersDao.save(list);
}
/**
* 根据 ID 查询单条数据
*/
@Test
public void test3(){
Users users = this.usersDao.findOne(13);
System.out.println(users);}
/**
* 查询全部数据
*/
@Test
public void test4(){
List<Users> list = (List<Users>)this.usersDao.findAll();
for (Users users : list) {
System.out.println(users);
}
}
/**
* 删除数据
*/
@Test
public void test5(){
this.usersDao.delete(13);
}
/**
* 更新数据 方式一
*/
@Test
public void test6(){
Users user = this.usersDao.findOne(12);
user.setUsername("王小红");
this.usersDao.save(user);
}
/**
* 更新数据 方式二
*/
@Test
@Transactional
@Rollback(false)
public void test7(){
Users user = this.usersDao.findOne(12);//持久化状态的
user.setUsername("王小小");
}
}

六、 PagingAndSortingRepository 接口 1 分页处理

1.1创建接口

/**
* PagingAndSortingRepository 接口讲解
* @author Administrator
*
*/
public interface UsersDao extends PagingAndSortingRepository<Users,
Integer>{
}
/**
* CrudRepository 接口测试
* @author Administrator
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RepositoryTest {
@Autowired
private UsersDao usersDao;
/**
* 分页
*/
@Test
public void test1(){
int page = 2; //page:当前页的索引。注意索引都是从 0 开始的。
int size = 3;// size:每页显示 3 条数据
Pageable pageable= new PageRequest(page, size);
Page<Users> p = this.usersDao.findAll(pageable);
System.out.println("数据的总条数:"+p.getTotalElements());System.out.println("总页数:"+p.getTotalPages());
List<Users> list = p.getContent();
for (Users users : list) {
System.out.println(users);
}
}
}

2 排序的处理 2.1测试代码

/**
* 对单列做排序处理
*/
@Test
public void test2(){
//Sort:该对象封装了排序规则以及指定的排序字段(对象的属性来表示)
//direction:排序规则
//properties:指定做排序的属性
Sort sort = new Sort(Direction.DESC,"userid");
List<Users> list = (List<Users>)this.usersDao.findAll(sort);
for (Users users : list) {
System.out.println(users);
}
}
/**
* 多列的排序处理
*/
@Test
public void test3(){
//Sort:该对象封装了排序规则以及指定的排序字段(对象的属性来表示)
//direction:排序规则
//properties:指定做排序的属性
Order order1 = new Order(Direction.DESC,"userage");
Order order2 = new Order(Direction.ASC,"username");
Sort sort = new Sort(order1,order2);
List<Users> list = (List<Users>)this.usersDao.findAll(sort);
for (Users users : list) {
System.out.println(users);
}
}

七、 JpaRepository 接口

JpaRepository 接口是我们开发时使用的最多的接口。其特点是可以帮助我们将其他接口 的方法的返回值做适配处理。可以使得我们在开发时更方便的使用这些方法

1 创建接

/**
* JpaRepository 接口讲解
* @author Administrator
*
*/
public interface UsersDao extends JpaRepository<Users, Integer>{
}

2 测试代码

/**
* JpaRepository 接口测试
* @author Administrator
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RepositoryTest {
@Autowired
private UsersDao usersDao;
/**
* 查询全部数据
*/
@Test
public void test1(){
List<Users> list = this.usersDao.findAll();
for (Users users : list) {
System.out.println(users);
}
}
}

八、 JpaSpecificationExecutor 接口 完成多条件查询,并且支持分页与排序

1 单条件查询

1.1创建接口

/**
* JpaSpecificationExecutor 接口讲解
* @author Administrator
*注意:JpaSpecificationExecutor<Users>:不能单独使用,需要配合着 jpa 中的
其他接口一起使用
*/
public interface UsersDao extends JpaRepository<Users,
Integer>,JpaSpecificationExecutor<Users>{
}
/**
* JpaRepository 接口测试
* @author Administrator
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RepositoryTest {
@Autowired
private UsersDao usersDao;
/**
* 需求:根据用户姓名查询数据
*/
@Test
public void test1(){
Specification<Users> spec = new Specification<Users>() {
/**
* @return Predicate:定义了查询条件
* @param Root<Users> root:根对象。封装了查询条件的对象* @param CriteriaQuery<?> query:定义了一个基本的查询.一般不
使用
* @param CriteriaBuilder cb:创建一个查询条件
*/
@Override
public Predicate toPredicate(Root<Users> root,
CriteriaQuery<?> query, CriteriaBuilder cb) {
Predicate pre = cb.equal(root.get("username"), "王五");
return pre;
}
};
List<Users> list = this.usersDao.findAll(spec);
for (Users users : list) {
System.out.println(users);
}
}
}

2 多条件查询

2.1给定查询条件方式一

/**
* 多条件查询 方式一
* 需求:使用用户姓名以及年龄查询数据
*/
@Test
public void test2(){
Specification<Users> spec = new Specification<Users>() {
@Override
public Predicate toPredicate(Root<Users> root,
CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<>();
list.add(cb.equal(root.get("username"),"王五"));
list.add(cb.equal(root.get("userage"),24));
//此时条件之间是没有任何关系的。
Predicate[] arr = new Predicate[list.size()];
return cb.and(list.toArray(arr));
}};
List<Users> list = this.usersDao.findAll(spec);
for (Users users : list) {
System.out.println(users);
}
}

2.2给定查询条件方式二

/**
* 多条件查询 方式二
* 需求:使用用户姓名或者年龄查询数据
*/
@Test
public void test3(){
Specification<Users> spec = new Specification<Users>() {
@Override
public Predicate toPredicate(Root<Users> root,
CriteriaQuery<?> query, CriteriaBuilder cb) {
return cb.or(cb.equal(root.get("username"),"王五
"),cb.equal(root.get("userage"), 25));
}
};
List<Users> list = this.usersDao.findAll(spec);
for (Users users : list) {
System.out.println(users);
}
}

3 分页

/**
* 需求:查询王姓用户,并且做分页处理
*/
@Test
public void test4(){
//条件
Specification<Users> spec = new Specification<Users>() {
@Overridepublic Predicate toPredicate(Root<Users> root,
CriteriaQuery<?> query, CriteriaBuilder cb) {
return cb.like(root.get("username").as(String.class),
"王%");
}
};
//分页
Pageable pageable = new PageRequest(2, 2);
Page<Users> page = this.usersDao.findAll(spec, pageable);
System.out.println("总条数:"+page.getTotalElements());
System.out.println("总页数:"+page.getTotalPages());
List<Users> list = page.getContent();
for (Users users : list) {
System.out.println(users);
}
}

4 排

/**
* 需求:查询数据库中王姓的用户,并且根据用户 id 做倒序排序
*/
@Test
public void test5(){
//条件
Specification<Users> spec = new Specification<Users>() {
@Override
public Predicate toPredicate(Root<Users> root,
CriteriaQuery<?> query, CriteriaBuilder cb) {
return cb.like(root.get("username").as(String.class),
"王%");
}
};
//排序
Sort sort = new Sort(Direction.DESC,"userid");
List<Users> list = this.usersDao.findAll(spec, sort);
for (Users users : list) {
System.out.println(users);
}}

5 分页与排序

/**
* 需求:查询数据库中王姓的用户,做分页处理,并且根据用户 id 做倒序排序
*/
@Test
public void test6(){
//排序等定义
Sort sort = new Sort(Direction.DESC,"userid");
//分页的定义
Pageable pageable = new PageRequest(2,2, sort);
//查询条件
Specification<Users> spec = new Specification<Users>() {
@Override
public Predicate toPredicate(Root<Users> root,
CriteriaQuery<?> query, CriteriaBuilder cb) {
return cb.like(root.get("username").as(String.class),
"王%");
}
};
Page<Users> page = this.usersDao.findAll(spec, pageable);
System.out.println("总条数:"+page.getTotalElements());
System.out.println("总页数:"+page.getTotalPages());
List<Users> list = page.getContent();
for (Users users : list) {
System.out.println(users);
}
}

九、 用户自定义 Repository 接口

1 创建接

public interface UsersRepository {
public Users findUserById(Integer userid);
}

2 使用接

/**
* 用户自定义 Repository 接口讲解
* @author Administrator
*/
public interface UsersDao extends JpaRepository<Users,
Integer>,JpaSpecificationExecutor<Users>,UsersRepository{
}

3 创建接口实现类

public class UsersDaoImpl implements UsersRepository {
@PersistenceContext(name="entityManagerFactory")
private EntityManager em;
@Override
public Users findUserById(Integer userid) {
System.out.println("MyRepository......");
return this.em.find(Users.class, userid);
}
}

4 编写测试代

/**
* JpaRepository 接口测试
* @author Administrator
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RepositoryTest {
@Autowired
private UsersDao usersDao;
/*** 需求:根据用户 ID 查询数据
*/
@Test
public void test1(){
Users users = this.usersDao.findUserById(5);
System.out.println(users);
}
}

 

推荐阅读