互联网分布式应用之SpringDataJPA

SpringDataJPA

Java 是第一大编程语言和开发平台。它有助于企业降低成本、缩短开发周期、推动创新以及改善应用服务。如今全球有数百万开发人员运行着超过 51 亿个 Java 虚拟机,Java 仍是企业和开发人员的首选开发平台。
  

课程内容的介绍

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

一、Spring整合Hibernate

1. 创建项目
创建一个普通的Maven项目即可。

互联网分布式应用之SpringDataJPA_第1张图片

   
2.添加相关的依赖
    
        
            org.springframework
            spring-orm
            5.1.6.RELEASE
        
        
            org.springframework
            spring-context
            5.1.6.RELEASE
        
        
            org.aspectj
            aspectjweaver
            1.9.2
        
        
            com.alibaba
            druid
            1.1.8
        
        
            mysql
            mysql-connector-java
            8.0.11
        
        
            org.hibernate
            hibernate-core
            5.0.7.Final
        
        
            junit
            junit
            4.12
            test
        
        
            org.springframework
            spring-test
            5.1.6.RELEASE
        
    
   
3. 添加相关的配置文件
添加数据库的配置文件和Spring的配置文件。


    
    
    
    
        
        
        
        
    

    
    
        
        
        
        
            
                true
                update
            
        
        
        
            
                com.bobo.pojo
            
        
    

    
    
        
    

    
    
        
    

    
    

    
    
     
4. 创建POJO
和表结构中的t_user表对应即可。
package com.bobo.pojo;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name="t_user")
public class Users implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="user_id")
    private Integer userId;

    @Column(name="user_name")
    private String userName;

    @Column(name="real_name")
    private String realName;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

}
   
5. 创建持久层
定义持久层接口,定义要实现的相关的方法。
package com.bobo.dao;

import com.bobo.pojo.Users;

import java.util.List;

public interface IUserDao {

    void insertUsers(Users users);

    void updateUsers(Users users);

    void deleteUsers(Users users);

    Users selectUsersById(Integer userId);

    List selectUsersByName(String userName);

    List selectUsersByNameUseSQL(String userName);

    List selectUsersByNameUseCriteria(String userName);
}
package com.bobo.dao.impl;

import com.bobo.dao.IUserDao;
import com.bobo.pojo.Users;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;


@Repository
public class UserDaoImpl implements IUserDao {

    @Autowired
    private HibernateTemplate template;

    @Override
    public void insertUsers(Users users) {
        this.template.save(users);
    }

    @Override
    public void updateUsers(Users users) {
        this.template.update(users);
    }

    @Override
    public void deleteUsers(Users users) {
        this.template.delete(users);
    }

    @Override
    public Users selectUsersById(Integer userId) {
        return this.template.get(Users.class,userId);
    }

    @Override
    public List selectUsersByName(String userName) {
        // 我们要执行特殊的查询操作 我们需要获取对应的Session对象
        Session session = this.template.getSessionFactory().getCurrentSession();
        // 通过Session对象创建Query对象 HQL 语句
        Query query = session.createQuery(" from Users where userName = :abc");
        Query queryTemp = query.setString("abc", userName);
        return queryTemp.list();
    }

    @Override
    public List selectUsersByNameUseSQL(String userName) {
        // 我们要执行特殊的查询操作 我们需要获取对应的Session对象
        Session session = this.template.getSessionFactory().getCurrentSession();
        // 通过Session对象创建Query对象 SQL 语句
        Query query = session.createSQLQuery("select * from t_user where user_name = ?")
                .addEntity(Users.class)
                .setString(0, userName);
        return query.list();
    }

    @Override
    public List selectUsersByNameUseCriteria(String userName) {
        Session session = this.template.getSessionFactory().getCurrentSession();
        Criteria criteria = session.createCriteria(Users.class);
        criteria.add(Restrictions.eq("userName",userName));
        return criteria.list();
    }
}
     
6. 单元测试
package com.bobo.test;

import com.bobo.dao.IUserDao;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test1 {

    @Autowired
    private IUserDao dao;

    @Test
    @Transactional
    @Rollback(false)
    public void testInsertUser(){
        Users user = new Users();
        user.setUserName("Tom");
        user.setRealName("张三丰");
        dao.insertUsers(user);
    }


    @Test
    @Transactional
    public void testQuery1(){
        Users users = this.dao.selectUsersById(22);
        System.out.println(users);
    }

    @Test
    @Transactional
    public void testQuery2(){
        List list = this.dao.selectUsersByNameUseSQL("Tom");
        for (Users users : list) {
            System.out.println(users);
        }
    }


}
  

互联网分布式应用之SpringDataJPA_第2张图片

  

互联网分布式应用之SpringDataJPA_第3张图片

  

二、Spring整合HibernateJPA

现如今的ORM框架还是比较多的比如Hibernate,TopLink以及OpenJPA等等,为了简化ORM框架的使用,JPA随之产生。
JPA是Java Persistence API的简称,中文名Java持久层API,由 Sun 公司提供了一对对于持久层操作的标准(接口+文档),说白了就是在各种ORM框架之上封装了一套API实现统一操作。同时又依赖各种ORM框架去实现。hibernate3.2版本后提供了对JPA的实现。
  
1. 创建项目
创建一个普通的Maven项目即可。

互联网分布式应用之SpringDataJPA_第4张图片

    
2. 添加相关的依赖
    
        
            org.springframework
            spring-orm
            5.1.6.RELEASE
        
        
            org.springframework
            spring-context
            5.1.6.RELEASE
        
        
            org.aspectj
            aspectjweaver
            1.9.2
        
        
            com.alibaba
            druid
            1.1.8
        
        
            mysql
            mysql-connector-java
            8.0.11
        
        
            org.hibernate
            hibernate-entitymanager
            5.0.7.Final
        
        
            junit
            junit
            4.12
            test
        
        
            org.springframework
            spring-test
            5.1.6.RELEASE
        
    
   
3. 添加相关的配置文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/logistics?characterEncoding=utf-8&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
     
Spring的配置文件


    
    
    
    
        
        
        
        
    

    
    
        
        
        
        
            
                
                
                
            
            
        
        
        
            
                com.bobo.pojo
            
        
    


    
    
        
    

    
    

    
    
  
4. 创建POJO
package com.bobo.pojo;


import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name="t_user")
public class Users implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="user_id")
    private Integer userId;

    @Column(name="user_name")
    private String userName;

    @Column(name="real_name")
    private String realName;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

    @Override
    public String toString() {
        return "Users{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                ", realName='" + realName + '\'' +
                '}';
    }
}
  
5. 创建持久层
package com.bobo.dao;

import com.bobo.pojo.Users;

import java.util.List;

public interface IUserDao {

    void insertUsers(Users users);

    void updateUsers(Users users);

    void deleteUsers(Users users);

    Users selectUsersById(Integer userId);

    List selectUsersByName(String userName);

    List selectUsersByNameUseSQL(String userName);

    List selectUsersByNameUseCriteria(String userName);
}
    
实现类
package com.bobo.dao.impl;

import com.bobo.dao.IUserDao;
import com.bobo.pojo.Users;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;


@Repository
public class UserDaoImpl implements IUserDao {


    @PersistenceContext(name = "entityManagerFactory")
    private EntityManager manager;

    @Override
    public void insertUsers(Users users) {
        manager.persist(users);
    }

    @Override
    public void updateUsers(Users users) {
        manager.merge(users);
    }

    @Override
    public void deleteUsers(Users users) {
        users = this.selectUsersById(users.getUserId());
        manager.remove(users);
    }

    @Override
    public Users selectUsersById(Integer userId) {
        return manager.find(Users.class,userId);
    }

    @Override
    public List selectUsersByName(String userName) {
        return manager.createQuery(" from Users where userName = :abc")
                .setParameter("abc",userName)
                .getResultList();
    }

    @Override
    public List selectUsersByNameUseSQL(String userName) {
        return manager.createNativeQuery("select * from t_user where user_name = ?",Users.class)
                .setParameter(1,userName)
                .getResultList();
    }

    @Override
    public List selectUsersByNameUseCriteria(String userName) {

        CriteriaBuilder builder = manager.getCriteriaBuilder();
        CriteriaQuery query = builder.createQuery(Users.class);
        Root root = query.from(Users.class);
        Predicate cate = builder.equal(root.get("userName"), userName);
        query.where(cate);
        TypedQuery typedQuery = manager.createQuery(query);
        return typedQuery.getResultList();
    }
}
    
6. 单元测试
package com.bobo.test;

import com.bobo.dao.IUserDao;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test1 {

    @Autowired
    private IUserDao dao;

    @Test
    @Transactional
    @Rollback(false)
    public void testInsertUser(){
        Users user = new Users();
        user.setUserName("Mic");
        user.setRealName("李逵");
        dao.insertUsers(user);
    }


    @Test
    @Transactional
    public void testQuery1(){
        Users users = this.dao.selectUsersById(22);
        System.out.println(users);
    }

    @Test
    @Transactional
    public void testQuery2(){
        List list = this.dao.selectUsersByNameUseSQL("Tom");
        for (Users users : list) {
            System.out.println(users);
        }
    }


}
  

互联网分布式应用之SpringDataJPA_第5张图片

  

互联网分布式应用之SpringDataJPA_第6张图片

  

三、SpringDataJPA介绍

1. 入门案例
1.1 创建项目
创建一个普通的Maven项目。
  
1.2 添加相关的依赖
    
        
            org.springframework
            spring-orm
            5.1.6.RELEASE
        
        
            org.springframework
            spring-context
            5.1.6.RELEASE
        
        
            org.aspectj
            aspectjweaver
            1.9.2
        
        
            com.alibaba
            druid
            1.1.8
        
        
            mysql
            mysql-connector-java
            8.0.11
        
        
            org.hibernate
            hibernate-entitymanager
            5.0.7.Final
        
        
            junit
            junit
            4.12
            test
        
        
            org.springframework
            spring-test
            5.1.6.RELEASE
        
        
            org.springframework.data
            spring-data-jpa
            1.9.0.RELEASE
        
    
  
1.3 添加配置文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/logistics?characterEncoding=utf-8&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
     
Spring的配置文件


    
    
    
    
        
        
        
        
    

    
    
        
        
        
        
            
                
                
                
            
            
        
        
        
            
                com.bobo.pojo
            
        
    


    
    
        
    

    
    

    
    

    
    
    
  
1.4 创建POJO对象
package com.bobo.pojo;


import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name="t_user")
public class Users implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="user_id")
    private Integer userId;

    @Column(name="user_name")
    private String userName;

    @Column(name="real_name")
    private String realName;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

    @Override
    public String toString() {
        return "Users{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                ", realName='" + realName + '\'' +
                '}';
    }
}
  
1.5 创建持久层
package com.bobo.dao;

import com.bobo.pojo.Users;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserDao extends JpaRepository {

}
     
1.6 单元测试
package com.bobo.test;

import com.bobo.dao.UserDao;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test1 {

    @Autowired
    private UserDao dao;


    @Test
    @Transactional
    @Rollback(false)
    public void test1(){
        Users user = new Users();
        user.setUserName("admin-jpa");
        user.setRealName("测试");
        dao.save(user);
    }
}
  

互联网分布式应用之SpringDataJPA_第7张图片

  

互联网分布式应用之SpringDataJPA_第8张图片

  
2. Repository接口
public interface Repository {
}
    
Repository 接口是 Spring Data JPA 中为我我们提供的所有接口中的顶层接口,而且是个标志接口,Repository 提供了两种查询方式的支持。
1)基于方法名称命名规则查询
2)基于@Query 注解查询
    
2.1 基于方法名称命名规则查询

互联网分布式应用之SpringDataJPA_第9张图片

      
package com.bobo.dao;

import com.bobo.pojo.Users;
import org.springframework.data.repository.Repository;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.List;

/**
 * Repository接口的使用
 */
public interface UserDaoRepository extends Repository {

    List findByUserNameIs(String string);

    List findByUserNameLike(String username);

    List findByUserNameAndRealNameIs(String name,String realName);
}
    
测试代码
package com.bobo.test;

import com.bobo.dao.UserDaoRepository;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test2 {

    @Autowired
    private UserDaoRepository dao;

    @Test
    @Transactional
    @Rollback(false)
    public void query1(){
        List list = this.dao.findByUserNameIs("Tom");
        for (Users users : list) {
            System.out.println(users);
        }
    }

    @Test
    @Transactional
    @Rollback(false)
    public void query2(){
        List list = this.dao.findByUserNameLike("Tom");
        for (Users users : list) {
            System.out.println(users);
        }
    }

    @Test
    @Transactional
    @Rollback(false)
    public void query3(){
        List list = this.dao.findByUserNameAndRealNameIs("Tom","张三丰");
        for (Users users : list) {
            System.out.println(users);
        }
    }
}
  

互联网分布式应用之SpringDataJPA_第10张图片

   
2.2 基于@Query 注解查询
通过上面的命令的方式使用的情况,如果查询条件比较复杂的情况下,那么方法的名称会很长,不是很方便而且容易出错,这时我们可以通过@Query注解来实现。
  
2.2.1 JPQL语句
JPQL:是通过Hibernate的HQL语句演变而来的,他和HQL语句很相似。
package com.bobo.dao;

import com.bobo.pojo.Users;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;

import java.util.List;

/**
 * Repository接口的使用
 * @Query
 *    JPQL语句
 *    SQL语句
 *    更新操作
 */
public interface UserDaoRepository2 extends Repository {

    @Query(value = " from Users where userName =?")
    List queryUsersByNameUseJPQL(String name);

    @Query(value = " from Users where userName like ?")
    List queryUserLikeNameUseJPQL(String name);

    @Query(value = " from Users where userName= ? and realName = ?")
    List queryUserByNameAndRealName(String userName,String realName);

}
     
单元测试
package com.bobo.test;

import com.bobo.dao.UserDaoRepository;
import com.bobo.dao.UserDaoRepository2;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test3 {

    @Autowired
    private UserDaoRepository2 dao;

    @Test
    @Transactional
    @Rollback(false)
    public void query1(){
        List list = this.dao.queryUsersByNameUseJPQL("Tom");
        for (Users users : list) {
            System.out.println(users);
        }
    }

    @Test
    @Transactional
    @Rollback(false)
    public void query2(){
        List list = this.dao.queryUserLikeNameUseJPQL("Tom");
        for (Users users : list) {
            System.out.println(users);
        }
    }

    @Test
    @Transactional
    @Rollback(false)
    public void query3(){
        List list = this.dao.queryUserByNameAndRealName("Tom","张三丰");
        for (Users users : list) {
            System.out.println(users);
        }
    }
}
  
2.2.2 SQL语句
声明接口
package com.bobo.dao;

import com.bobo.pojo.Users;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;

import java.util.List;

/**
 * Repository接口的使用
 * @Query
 *    JPQL语句
 *    SQL语句
 *    更新操作
 */
public interface UserDaoRepository3 extends Repository {

    // 在使用@Query注解 查询SQL语句的时候 nativeQuery默认是false,我们需要设置为true
    @Query(value = "select * from t_user where user_name=?",nativeQuery = true)
    List queryUsersByNameUseSQL(String name);

    @Query(value = "select * from t_user where user_name like ?" ,nativeQuery = true)
    List queryUserLikeNameUseSQL(String name);

    @Query(value = "select * from t_user where user_name = ? and real_name = ?" , nativeQuery = true)
    List queryUserByNameAndRealName(String userName,String realName);

}
    
单元测试
package com.bobo.test;

import com.bobo.dao.UserDaoRepository2;
import com.bobo.dao.UserDaoRepository3;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test4 {

    @Autowired
    private UserDaoRepository3 dao;

    @Test
    @Transactional
    @Rollback(false)
    public void query1(){
        List list = this.dao.queryUsersByNameUseSQL("Tom");
        for (Users users : list) {
            System.out.println(users);
        }
    }

    @Test
    @Transactional
    @Rollback(false)
    public void query2(){
        List list = this.dao.queryUserLikeNameUseSQL("Tom");
        for (Users users : list) {
            System.out.println(users);
        }
    }

    @Test
    @Transactional
    @Rollback(false)
    public void query3(){
        List list = this.dao.queryUserByNameAndRealName("Tom","张三丰");
        for (Users users : list) {
            System.out.println(users);
        }
    }
}
  

互联网分布式应用之SpringDataJPA_第11张图片

   
2.2.3 完成更新数据
@Query注解可以完成数据更新操作,但是不能实现数据的添加和删除操作。
@Query(value = "update Users set userName = ? where userId=?")
@Modifying// 被@Modifying修饰的方法是一个更新操作
void updateUserNameById(String userName,Integer userId);
  
测试
@Test
@Transactional
@Rollback(false)
public void updateTest(){
    this.dao.updateUserNameById("Tommm",25);
}
  

互联网分布式应用之SpringDataJPA_第12张图片

  
3. CrudRepository接口
CrudRepository接口继承自Repository接口,所以Repository接口具有的功能CrudRepository接口都具有,而且又扩展了CRUD相关的功能。
@NoRepositoryBean
public interface CrudRepository extends Repository {
     S save(S var1);
     Iterable save(Iterable var1);
    T findOne(ID var1);
    boolean exists(ID var1);
    Iterable findAll();
    Iterable findAll(Iterable var1);
    long count();
    void delete(ID var1);
    void delete(T var1);
    void delete(Iterable var1);
    void deleteAll();
}
    
应用声明接口
/**
* CrudRepository接口的使用
*/
public interface UserDaoCrudRepository extends CrudRepository {
}
     
单元测试
package com.bobo.test;

import com.bobo.dao.UserDaoCrudRepository;
import com.bobo.dao.UserDaoRepository3;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.experimental.theories.suppliers.TestedOn;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.support.CustomSQLErrorCodesTranslation;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test5 {

    @Autowired
    private UserDaoCrudRepository dao;

    /**
     * 添加数据
     */
    @Test
    public void test1(){
        Users user = new Users();
        user.setRealName("成龙");
        user.setUserName("chengnong");
        dao.save(user);
    }

    /**
     * 批量添加数据
     */
    @Test
    public void test2(){
        List list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Users user = new Users();
            user.setRealName("成龙"+i);
            user.setUserName("chengnong"+i);
            list.add(user);
        }
        dao.save(list);
    }

    /**
     * 查询单条数据
     */
    @Test
    public void test3(){
        Users user = dao.findOne(25);
        System.out.println(user);
    }

    /**
     * 查询所有的数据
     */
    @Test
    public void test4(){
        Iterable list = dao.findAll();
        Iterator iterator = list.iterator();
        while(iterator.hasNext()){
            Users user = iterator.next();
            System.out.println(user);
        }
    }

    /**
     * 删除数据
     */
    @Test
    public void delete1(){
        dao.delete(32);
    }

    /**
     * 更新数据
     */
    @Test
    public void update1(){
        // 根据save方法来实现 如果Users对象的userId属性不为空则update
        Users user = dao.findOne(34);
        user.setUserName("hahahaha");
        dao.save(user);
    }

    /**
     * 更新数据 方式二
     */
    @Test
    @Transactional
    @Rollback(false)
    public void update2(){
        Users user = dao.findOne(34);
        user.setUserName("aaaa"); // User 是一个持久化的状态
    }
}
  
4.PagingAndSortingRepository接口
PagingAndSortingRepository继承自CrudRepository接口,那么显然PagingAndSortingRepository就具备了CrudRepository接口的相关的功能,同时也扩展了分页和排序的功能。
@NoRepositoryBean
public interface PagingAndSortingRepository extends CrudRepository {
    // 排序的支持
    Iterable findAll(Sort var1);
    // 分页的支持
    Page findAll(Pageable var1);
}
  
创建接口文件
package com.bobo.dao;

import com.bobo.pojo.Users;
import org.springframework.data.repository.PagingAndSortingRepository;

/**
 * PagingAndSortingRepository接口的使用
 *    新增的功能是
 *       分页
 *       排序
 *    注意本接口不支持条件查询
 */
public interface UserDaoPageAndSortRepository extends PagingAndSortingRepository {
}
  
分页测试
package com.bobo.test;

import com.bobo.dao.UserDaoCrudRepository;
import com.bobo.dao.UserDaoPageAndSortRepository;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test6 {

    @Autowired
    private UserDaoPageAndSortRepository dao;

    /**
     * 分页查询
     */
    @Test
    public void test1(){
        int page = 1; // page:当前分页的索引  从0开始
        int size = 5; // size:每页显示的条数
        PageRequest pageable = new PageRequest(page,size);
        Page pages = dao.findAll(pageable);
        System.out.println("总的条数:" + pages.getTotalElements());
        System.out.println("总的页数:" + pages.getTotalPages());
        List list = pages.getContent();
        for (Users user : list) {
            System.out.println(user);
        }
    }
}
  

互联网分布式应用之SpringDataJPA_第13张图片

  
排序功能
    /**
     * 排序
     */
    @Test
    public void test2(){

        // Sort.Direction.DESC 降序 ASC 升序
        Sort sort = new Sort(Sort.Direction.DESC,"userId");
        List list = (List) this.dao.findAll(sort);
        for (Users users : list) {
            System.out.println(users);
        }
    }
    

互联网分布式应用之SpringDataJPA_第14张图片

  
多条件排序
    /**
     * 多条件排序
     */
    @Test
    public void test3(){
        Sort.Order order1 = new Sort.Order(Sort.Direction.DESC,"realName");
        Sort.Order order2 = new Sort.Order(Sort.Direction.ASC,"userId");
        Sort sort = new Sort(order1,order2);
        List list = (List) this.dao.findAll(sort);
        for (Users users : list) {
            System.out.println(users);
        }

    }
  

互联网分布式应用之SpringDataJPA_第15张图片

  
5. JpaRepository接口
JpaRepository接口是我们开发时使用最多接口,其特点是可以帮助我们将其他接口的方法的返回值做适配处理,可以使我们在开发的时候更方便的使用这些方法。
@NoRepositoryBean
public interface JpaRepository extends PagingAndSortingRepository {
    List findAll();
    List findAll(Sort var1);
    List findAll(Iterable var1);
     List save(Iterable var1);
    void flush();
     S saveAndFlush(S var1);
    void deleteInBatch(Iterable var1);
    void deleteAllInBatch();
    T getOne(ID var1);
}
  
6. JpaSpecificationExecutor
提供的有多条件查询,并支持分页和排序功能,此接口不能单独使用,需要和其他的接口一块使用。
/**
* JpaSpecificationExecutor的使用
* JpaSpecificationExecutor 是不能够单独使用的。需要配置JPA中的其他的接口一块来使用
*/
public interface UserDaoSpecfication extends JpaRepository, JpaSpecificationExecutor {
}
     
6.1 单条件查询
package com.bobo.test;

import com.bobo.dao.UserDaoSpecfication;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test7 {

    @Autowired
    private UserDaoSpecfication dao;

    @Test
    public void test1(){
        Specification speci = new Specification() {
            /**
             * 定义查询条件
             * @param root 根对象  封装查询条件的对象
             * @param criteriaQuery 基本的查询
             * @param criteriaBuilder 创建查询条件
             * @return
             */
            @Override
            public Predicate toPredicate(Root root
                    , CriteriaQuery criteriaQuery
                    , CriteriaBuilder criteriaBuilder) {
                Predicate pre = criteriaBuilder.equal(root.get("userName"),"Tommm");
                return pre;
            }
        };

        List list = dao.findAll(speci);
        for (Users users : list) {
            System.out.println(users);
        }
    }
}
  

互联网分布式应用之SpringDataJPA_第16张图片

  
6.2 多条件
    /**
     * 多条件查询
     */
    @Test
    public void test2(){
        Specification spec = new Specification() {
            /**
             * 指定查询的条件
             * @param root
             * @param criteriaQuery
             * @param criteriaBuilder
             * @return
             */
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List list = new ArrayList<>();
                list.add(criteriaBuilder.equal(root.get("userName"),"Tommm"));
                list.add(criteriaBuilder.equal(root.get("realName"),"张三丰"));
                Predicate[] arr = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(arr));
            }
        };
        List list = dao.findAll(spec);
        for (Users users : list) {
            System.out.println(users);
        }
    }
  

互联网分布式应用之SpringDataJPA_第17张图片

  
6.3 分页
    /**
     * 单条件+分页
     */
    @Test
    public void test3(){
        Specification speci = new Specification() {
            /**
             * 定义查询条件
             * @param root 根对象  封装查询条件的对象
             * @param criteriaQuery 基本的查询
             * @param criteriaBuilder 创建查询条件
             * @return
             */
            @Override
            public Predicate toPredicate(Root root
                    , CriteriaQuery criteriaQuery
                    , CriteriaBuilder criteriaBuilder) {
                Predicate pre = criteriaBuilder.equal(root.get("userName"),"Tommm");
                return pre;
            }
        };

        Pageable pagealbe = (Pageable) new PageRequest(0,3);
        Page page = dao.findAll(speci, pagealbe);
        System.out.println(page.getTotalElements());
        System.out.println(page.getTotalPages());
        List content = page.getContent();
        System.out.println(content);

    }
  

互联网分布式应用之SpringDataJPA_第18张图片

  
6.4 排序
    /**
     * 单条件+排序
     */
    @Test
    public void test4(){
        Specification speci = new Specification() {
            /**
             * 定义查询条件
             * @param root 根对象  封装查询条件的对象
             * @param criteriaQuery 基本的查询
             * @param criteriaBuilder 创建查询条件
             * @return
             */
            @Override
            public Predicate toPredicate(Root root
                    , CriteriaQuery criteriaQuery
                    , CriteriaBuilder criteriaBuilder) {
                Predicate pre = criteriaBuilder.equal(root.get("userName"),"Tommm");
                return pre;
            }
        };

        Sort sort = new Sort(Sort.Direction.DESC,"userId");
        List list = dao.findAll(speci, sort);
        System.out.println(list);

    }
  

互联网分布式应用之SpringDataJPA_第19张图片

  
6.5 分页和排序
    /**
     * 单条件+分页 + 排序
     */
    @Test
    public void test5(){
        Specification speci = new Specification() {
            /**
             * 定义查询条件
             * @param root 根对象  封装查询条件的对象
             * @param criteriaQuery 基本的查询
             * @param criteriaBuilder 创建查询条件
             * @return
             */
            @Override
            public Predicate toPredicate(Root root
                    , CriteriaQuery criteriaQuery
                    , CriteriaBuilder criteriaBuilder) {
                Predicate pre = criteriaBuilder.equal(root.get("userName"),"Tommm");
                return pre;
            }
        };
        Sort sort = new Sort(Sort.Direction.DESC,"userId");
        // 封装分页对象的时候我们可以直接指定 排序的规则
        Pageable pagealbe = (Pageable) new PageRequest(0,3,sort);
        Page page = dao.findAll(speci, pagealbe);
        System.out.println(page.getTotalElements());
        System.out.println(page.getTotalPages());
        List content = page.getContent();
        System.out.println(content);

    }
  

互联网分布式应用之SpringDataJPA_第20张图片

  

四、SpringBoot整合SpringDataJPA

1. 添加依赖

互联网分布式应用之SpringDataJPA_第21张图片

  
2. 添加配置文件
# jdbc 的相关信息
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/logistics?
characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456

# 配置连接池信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

# 配置jpa的相关参数
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
    
3. 创建POJO
package com.bobo.pojo;

import javax.persistence.*;
import java.io.Serializable;

@Table(name = "t_user")
@Entity
public class Users implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="user_id")
    private Integer userId;

    @Column(name="user_name")
    private String usreName;

    @Column(name="real_name")
    private String realName;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUsreName() {
        return usreName;
    }

    public void setUsreName(String usreName) {
        this.usreName = usreName;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }
}
  
4. 创建接口
package com.bobo.dao;

import com.bobo.pojo.Users;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UsersRepository extends JpaRepository {
}
  
5. 测试
package com.bobo;

import com.bobo.dao.UsersRepository;
import com.bobo.pojo.Users;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringdatajpaSpringbootApplicationTests {

    @Autowired
    private UsersRepository dao;

    @Test
    void contextLoads() {
        Users users = new Users();
        users.setUsreName("test1");
        users.setRealName("测试数据");
        dao.save(users);
    }

}
  

互联网分布式应用之SpringDataJPA_第22张图片

你可能感兴趣的:(微服务高并发必备技术栈,java,开发语言,SpringDataJPA)