Spring Data JPA 框架基础
Spirng Data JPA && JPA 规范 && Hibernate 之间的关系
ORM思想:Object Relational Mapping。对象关系映射。通过操作 POJO 对象达到操作数据库的目的。
Hibernate 框架:基于 ORM 思想封装了 JDBC操作。
JPA规范:Java Persistence API。由 SUN 公司提出的 Java 持久化 API。制定了一系列的接口和抽象类。Hibernate 框架满足 JPA 规范。
Spirng Data JPA:封装了 JPA 规范。利用满足 JPA 规范的 Hibernate 框架 进行数据持久化。
Spring Data JPA 应用
pom.xml
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.1.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.0.Final</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<!-- 读取配置文件 -->
<context:property-placeholder location="jdbc.properties"/>
<!-- 配置连接池信息 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置 entityManagerFactory 类似 Mybatis 中的 SqlSessionFactory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- 配置数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置 persistence 实体所在的包 fix:No persistence units parsed -->
<property name="packagesToScan" value="com.demo.pojo"/>
<!-- 指定 JPA 的具体实现 fix:No PersistenceProvider specified in EntityManagerFactory configuration -->
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
</property>
<!-- 配置 Hibernate 框架的执行细节 -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- 是否打印 SQL -->
<property name="showSql" value="true"/>
</bean>
</property>
</bean>
<!-- 配置 JPA 使用的 dao 层接口所在包 -->
<jpa:repositories base-package="com.demo.dao"/>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"/>
</beans>
编写实体类
@Entity
@Table(name = "tb_resume")
public class Resume {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@Column(name = "address")
private String address;
@Column(name = "phone")
private String phone;
}
编写接口类
public interface ResumeDao extends JpaRepository<Resume, Long>{}
简单CRUD
// 根据ID查询
Optional<Resume> resumeOptional = resumeDao.findById(1L);
// 根据创建出来的条件查询
Resume resume = new Resume();
resume.setName("张三");
resume.setId(1L);
Example<Resume> resumeExample = Example.of(resume);
Optional<Resume> resumeOptional = resumeDao.findOne(resumeExample);
// 查询所有
List<Resume> resumeList = resumeDao.findAll();
// 如果给了主键就是更新;如果没给主键就是插入
// 返回的实体是插入或更新后的内容;含ID
// 如果传入的实体有的属性没有赋值 会 update 掉原有的值
Resume resume = new Resume();
resume.setName("李四");
resume.setId(1L);
Resume result = resumeDao.save(resume);
// 根据ID删除
// 删除没有返回值
resumeDao.deleteById(1L);
排序
//add properties "id" to fix:You have to provide at least one property to sort by!
Sort sort = new Sort(Sort.Direction.DESC, "id");
List<Resume> resumeList = resumeDao.findAll(sort);
JPQL 查询方式
// interface ResumeDao 中添加
@Query("from Resume where id = ?1 and name like ?2")
List<Resume> findByJPQL(Long id, String name);
List<Resume> resumeList = resumeDao.findByJPQL(2L, "%李%");
普通SQL查询方式
// interface ResumeDao 中添加
@Query(value = "select * from tb_resume where id = ?1 and name like ?2", nativeQuery = true)
List<Resume> findBySQL(Long id, String name);
List<Resume> resumeList = resumeDao.findBySQL(2L, "%李%");
接口中定义方法查询方式
// interface ResumeDao 中添加
// 方法名以 find 开头 - 属性名(首字母大写)- 查询方式(模糊查询、等价查询),不写查询方式默认等价查询
List<Resume> findByIdAndNameLike(Long id, String name);
List<Resume> resumeList = resumeDao.findByIdAndNameLike(2L, "%李%");
动态查询 && 分页查询
// interface ResumeDao 需要继承 JpaSpecificationExecutor<Resume>
/*
动态查询
root 获取需要查询的对象属性
CriteriaBuilder 构建查询条件
*/
Specification<Resume> specification = (Specification<Resume>) (root, query, criteriaBuilder) -> {
Path<Object> id = root.get("id");
Path<Object> name = root.get("name");
Predicate predicate1 = criteriaBuilder.equal(id, 2L);
Predicate predicate2 = criteriaBuilder.like(name.as(String.class), "%李%");
return criteriaBuilder.and(predicate1, predicate2);
};
Resume resume = resumeDao.findOne(specification).get();
/*
分页查询
第一个参数:当前查询的页数,从0开始
第二个参数:当页查询的数量
*/
Pageable pageable = PageRequest.of(0,2);
Page<Resume> resumePage = resumeDao.findAll(pageable);
// 总共多少页
System.out.println(resumePage.getTotalPages());
// 总共多少条
System.out.println(resumePage.getTotalElements());
List<Resume> resumeList = resumePage.getContent();
参考git:https://gitee.com/zhangyizhou/learning-spring-data-jpa-demo.git