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项目即可。
2.添加相关的依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.7.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
</dependencies>
3. 添加相关的配置文件
添加数据库的配置文件和Spring的配置文件。
<?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:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
">
<!-- 引入db.properties文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 创建druid 的数据源 -->
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<property name="url" value="${jdbc.url}" />
<property name="driverClassName" value="${jdbc.driver}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 配置Hibernate的SessionFactory对象 -->
<bean class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" id="sessionFactory">
<!-- 关联数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置Hibernate的属性信息 -->
<property name="hibernateProperties">
<props>
<prop key="show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- 扫描路径 -->
<property name="packagesToScan">
<list>
<value>com.bobo.pojo</value>
</list>
</property>
</bean>
<!-- 配置HibernateTemplate对象 -->
<bean class="org.springframework.orm.hibernate5.HibernateTemplate" id="hibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 配置事务管理-->
<bean class="org.springframework.orm.hibernate5.HibernateTransactionManager" id="transactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置开启事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 配置扫描路径 -->
<context:component-scan base-package="com.bobo" />
</beans>
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<Users> selectUsersByName(String userName);
List<Users> selectUsersByNameUseSQL(String userName);
List<Users> 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<Users> 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<Users> 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<Users> 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<Users> list = this.dao.selectUsersByNameUseSQL("Tom");
for (Users users : list) {
System.out.println(users);
}
}
}
二、Spring整合HibernateJPA
现如今的ORM框架还是比较多的比如Hibernate,TopLink以及OpenJPA等等,为了简化ORM框架的使用,JPA随之产生。
JPA是Java Persistence API的简称,中文名Java持久层API,由 Sun 公司提供了一对对于持久层操作的标准(接口+文档),说白了就是在各种ORM框架之上封装了一套API实现统一操作。同时又依赖各种ORM框架去实现。hibernate3.2版本后提供了对JPA的实现。
1. 创建项目
创建一个普通的Maven项目即可。
2. 添加相关的依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.7.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
</dependencies>
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的配置文件
<?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:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
">
<!-- 引入db.properties文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 创建druid 的数据源 -->
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<property name="url" value="${jdbc.url}" />
<property name="driverClassName" value="${jdbc.driver}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 配置Hibernate的SessionFactory对象 -->
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="sessionFactory">
<!-- 关联数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置Hibernate的属性信息 -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL"/>
<property name="generateDdl" value="true"/>
<property name="showSql" value="true"/>
</bean>
<!--<props>
<prop key="show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>-->
</property>
<!-- 扫描路径 -->
<property name="packagesToScan">
<list>
<value>com.bobo.pojo</value>
</list>
</property>
</bean>
<!-- 配置事务管理-->
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="sessionFactory" />
</bean>
<!-- 配置开启事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 配置扫描路径 -->
<context:component-scan base-package="com.bobo" />
</beans>
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<Users> selectUsersByName(String userName);
List<Users> selectUsersByNameUseSQL(String userName);
List<Users> 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<Users> selectUsersByName(String userName) {
return manager.createQuery(" from Users where userName = :abc")
.setParameter("abc",userName)
.getResultList();
}
@Override
public List<Users> selectUsersByNameUseSQL(String userName) {
return manager.createNativeQuery("select * from t_user where user_name = ?",Users.class)
.setParameter(1,userName)
.getResultList();
}
@Override
public List<Users> selectUsersByNameUseCriteria(String userName) {
CriteriaBuilder builder = manager.getCriteriaBuilder();
CriteriaQuery<Users> query = builder.createQuery(Users.class);
Root<Users> root = query.from(Users.class);
Predicate cate = builder.equal(root.get("userName"), userName);
query.where(cate);
TypedQuery<Users> 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<Users> list = this.dao.selectUsersByNameUseSQL("Tom");
for (Users users : list) {
System.out.println(users);
}
}
}
三、SpringDataJPA介绍
1. 入门案例
1.1 创建项目
创建一个普通的Maven项目。
1.2 添加相关的依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.7.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
</dependencies>
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的配置文件
<?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: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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
">
<!-- 引入db.properties文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 创建druid 的数据源 -->
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<property name="url" value="${jdbc.url}" />
<property name="driverClassName" value="${jdbc.driver}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 配置Hibernate的SessionFactory对象 id必须得是 : entityManagerFactory -->
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactory">
<!-- 关联数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置Hibernate的属性信息 -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL"/>
<property name="generateDdl" value="true"/>
<property name="showSql" value="true"/>
</bean>
<!--<props>
<prop key="show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>-->
</property>
<!-- 扫描路径 -->
<property name="packagesToScan">
<list>
<value>com.bobo.pojo</value>
</list>
</property>
</bean>
<!-- 配置事务管理-->
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- 配置开启事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 配置扫描路径 -->
<context:component-scan base-package="com.bobo" />
<!-- Spring Data Jpa 配置-->
<!-- 配置Dao的扫描 -->
<jpa:repositories base-package="com.bobo.dao" />
</beans>
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<Users,Integer> {
}
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);
}
}
2. Repository接口
public interface Repository<T, ID extends Serializable> {
}
Repository 接口是 Spring Data JPA 中为我我们提供的所有接口中的顶层接口,而且是个标志接口,Repository 提供了两种查询方式的支持。
1)基于方法名称命名规则查询
2)基于@Query 注解查询
2.1 基于方法名称命名规则查询
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<Users, Integer> {
List<Users> findByUserNameIs(String string);
List<Users> findByUserNameLike(String username);
List<Users> 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<Users> list = this.dao.findByUserNameIs("Tom");
for (Users users : list) {
System.out.println(users);
}
}
@Test
@Transactional
@Rollback(false)
public void query2(){
List<Users> list = this.dao.findByUserNameLike("Tom");
for (Users users : list) {
System.out.println(users);
}
}
@Test
@Transactional
@Rollback(false)
public void query3(){
List<Users> list = this.dao.findByUserNameAndRealNameIs("Tom","张三丰");
for (Users users : list) {
System.out.println(users);
}
}
}
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<Users, Integer> {
@Query(value = " from Users where userName =?")
List<Users> queryUsersByNameUseJPQL(String name);
@Query(value = " from Users where userName like ?")
List<Users> queryUserLikeNameUseJPQL(String name);
@Query(value = " from Users where userName= ? and realName = ?")
List<Users> 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<Users> list = this.dao.queryUsersByNameUseJPQL("Tom");
for (Users users : list) {
System.out.println(users);
}
}
@Test
@Transactional
@Rollback(false)
public void query2(){
List<Users> list = this.dao.queryUserLikeNameUseJPQL("Tom");
for (Users users : list) {
System.out.println(users);
}
}
@Test
@Transactional
@Rollback(false)
public void query3(){
List<Users> 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<Users, Integer> {
// 在使用@Query注解 查询SQL语句的时候 nativeQuery默认是false,我们需要设置为true
@Query(value = "select * from t_user where user_name=?",nativeQuery = true)
List<Users> queryUsersByNameUseSQL(String name);
@Query(value = "select * from t_user where user_name like ?" ,nativeQuery = true)
List<Users> queryUserLikeNameUseSQL(String name);
@Query(value = "select * from t_user where user_name = ? and real_name = ?" , nativeQuery = true)
List<Users> 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<Users> list = this.dao.queryUsersByNameUseSQL("Tom");
for (Users users : list) {
System.out.println(users);
}
}
@Test
@Transactional
@Rollback(false)
public void query2(){
List<Users> list = this.dao.queryUserLikeNameUseSQL("Tom");
for (Users users : list) {
System.out.println(users);
}
}
@Test
@Transactional
@Rollback(false)
public void query3(){
List<Users> list = this.dao.queryUserByNameAndRealName("Tom","张三丰");
for (Users users : list) {
System.out.println(users);
}
}
}
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);
}
3. CrudRepository接口
CrudRepository接口继承自Repository接口,所以Repository接口具有的功能CrudRepository接口都具有,而且又扩展了CRUD相关的功能。
@NoRepositoryBean
public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {
<S extends T> S save(S var1);
<S extends T> Iterable<S> save(Iterable<S> var1);
T findOne(ID var1);
boolean exists(ID var1);
Iterable<T> findAll();
Iterable<T> findAll(Iterable<ID> var1);
long count();
void delete(ID var1);
void delete(T var1);
void delete(Iterable<? extends T> var1);
void deleteAll();
}
应用声明接口
/**
* CrudRepository接口的使用
*/
public interface UserDaoCrudRepository extends CrudRepository<Users,Integer> {
}
单元测试
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<Users> 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<Users> list = dao.findAll();
Iterator<Users> 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<T, ID extends Serializable> extends CrudRepository<T, ID> {
// 排序的支持
Iterable<T> findAll(Sort var1);
// 分页的支持
Page<T> findAll(Pageable var1);
}
创建接口文件
package com.bobo.dao;
import com.bobo.pojo.Users;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
* PagingAndSortingRepository接口的使用
* 新增的功能是
* 分页
* 排序
* 注意本接口不支持条件查询
*/
public interface UserDaoPageAndSortRepository extends PagingAndSortingRepository<Users,Integer> {
}
分页测试
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<Users> pages = dao.findAll(pageable);
System.out.println("总的条数:" + pages.getTotalElements());
System.out.println("总的页数:" + pages.getTotalPages());
List<Users> list = pages.getContent();
for (Users user : list) {
System.out.println(user);
}
}
}
排序功能
/**
* 排序
*/
@Test
public void test2(){
// Sort.Direction.DESC 降序 ASC 升序
Sort sort = new Sort(Sort.Direction.DESC,"userId");
List<Users> list = (List<Users>) this.dao.findAll(sort);
for (Users users : list) {
System.out.println(users);
}
}
多条件排序
/**
* 多条件排序
*/
@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<Users> list = (List<Users>) this.dao.findAll(sort);
for (Users users : list) {
System.out.println(users);
}
}
5. JpaRepository接口
JpaRepository接口是我们开发时使用最多接口,其特点是可以帮助我们将其他接口的方法的返回值做适配处理,可以使我们在开发的时候更方便的使用这些方法。
@NoRepositoryBean
public interface JpaRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID> {
List<T> findAll();
List<T> findAll(Sort var1);
List<T> findAll(Iterable<ID> var1);
<S extends T> List<S> save(Iterable<S> var1);
void flush();
<S extends T> S saveAndFlush(S var1);
void deleteInBatch(Iterable<T> var1);
void deleteAllInBatch();
T getOne(ID var1);
}
6. JpaSpecificationExecutor
提供的有多条件查询,并支持分页和排序功能,此接口不能单独使用,需要和其他的接口一块使用。
/**
* JpaSpecificationExecutor的使用
* JpaSpecificationExecutor 是不能够单独使用的。需要配置JPA中的其他的接口一块来使用
*/
public interface UserDaoSpecfication extends JpaRepository<Users,Integer>, 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<Users> speci = new Specification<Users>() {
/**
* 定义查询条件
* @param root 根对象 封装查询条件的对象
* @param criteriaQuery 基本的查询
* @param criteriaBuilder 创建查询条件
* @return
*/
@Override
public Predicate toPredicate(Root<Users> root
, CriteriaQuery<?> criteriaQuery
, CriteriaBuilder criteriaBuilder) {
Predicate pre = criteriaBuilder.equal(root.get("userName"),"Tommm");
return pre;
}
};
List<Users> list = dao.findAll(speci);
for (Users users : list) {
System.out.println(users);
}
}
}
6.2 多条件
/**
* 多条件查询
*/
@Test
public void test2(){
Specification<Users> spec = new Specification<Users>() {
/**
* 指定查询的条件
* @param root
* @param criteriaQuery
* @param criteriaBuilder
* @return
*/
@Override
public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
List<Predicate> 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<Users> list = dao.findAll(spec);
for (Users users : list) {
System.out.println(users);
}
}
6.3 分页
/**
* 单条件+分页
*/
@Test
public void test3(){
Specification<Users> speci = new Specification<Users>() {
/**
* 定义查询条件
* @param root 根对象 封装查询条件的对象
* @param criteriaQuery 基本的查询
* @param criteriaBuilder 创建查询条件
* @return
*/
@Override
public Predicate toPredicate(Root<Users> 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);
}
6.4 排序
/**
* 单条件+排序
*/
@Test
public void test4(){
Specification<Users> speci = new Specification<Users>() {
/**
* 定义查询条件
* @param root 根对象 封装查询条件的对象
* @param criteriaQuery 基本的查询
* @param criteriaBuilder 创建查询条件
* @return
*/
@Override
public Predicate toPredicate(Root<Users> root
, CriteriaQuery<?> criteriaQuery
, CriteriaBuilder criteriaBuilder) {
Predicate pre = criteriaBuilder.equal(root.get("userName"),"Tommm");
return pre;
}
};
Sort sort = new Sort(Sort.Direction.DESC,"userId");
List<Users> list = dao.findAll(speci, sort);
System.out.println(list);
}
6.5 分页和排序
/**
* 单条件+分页 + 排序
*/
@Test
public void test5(){
Specification<Users> speci = new Specification<Users>() {
/**
* 定义查询条件
* @param root 根对象 封装查询条件的对象
* @param criteriaQuery 基本的查询
* @param criteriaBuilder 创建查询条件
* @return
*/
@Override
public Predicate toPredicate(Root<Users> 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);
}
四、SpringBoot整合SpringDataJPA
1. 添加依赖
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<Users,Integer> {
}
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);
}
}