Spring Data是一个用于简化数据库访问,支持云服务的开源框架。目标是使数据库访问变得方便快捷。公司的ORM框架,均采用Spring Data JPA。
JPA的全称是Java Persistence API,Persistence 是持久化的意思。所以,中文全称是"JAVA对象持久化的 API"。简单来说,可以理解为是一种JAVA的标准规范,这个规范为JAVA对象的持久化制定了一些标准的接口。要注意的是,JPA只是一个接口规范,而不是实现。具体实现由各供应商来完成,例如Hibernate,TopLink,OpenJPA都很好地实现了JPA接口。
简而言之:Spring Data JPA只是Spring Data中的一个子模块;JPA是一套标准接口,而Hibernate是JPA的实现;Spring Data JPA 底层默认实现是使用Hibernate。
Spring DataJPA 的首个接口就是Repository,它是一个标记接口。只要我们的接口实现这个接口,那么我们就相当于在使用Spring Data JPA了。(只要我们实现了这个接口,我们就可以使用"按照方法命名规则"来进行查询。
Spring Data JPA入门小demo
1.创建数据库
2.创建Maven工程(jar
3.在pom.xml文件中添加依赖
<properties>
<spring.version>4.2.4.RELEASE</spring.version>
<hibernate.version>5.0.7.Final</hibernate.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<c3p0.version>0.9.1.2</c3p0.version>
<mysql.version>5.1.6</mysql.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- junit单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- spring beg -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring end -->
<!-- hibernate beg -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.1.Final</version>
</dependency>
<!-- hibernate end -->
<!-- c3p0 beg -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
<!-- c3p0 end -->
<!-- log end -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<!-- el beg 使用spring data jpa 必须引入 -->
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
<!-- el end -->
</dependencies>
4.在src/main/resources下创建applicationContext.xml配置文件(Spring和Spring Data JPA整合
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.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">
<!--1 员 dataSource 数据库连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="root"/>
<property name="password" value="123456"/>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springdatajpa9502"/>
</bean>
<!--2 工 工厂类对象-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!--配置数据源-->
<property name="dataSource" ref="dataSource"/>
<!--实体类的包扫描-->
<property name="packagesToScan" value="cn.zf.jpa.entity"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="MYSQL"/>
</bean>
</property>
</bean>
<!--3 是 事务配置-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--开启事物-->
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="get*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* cn.zf.jpa.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
</aop:config>
<!--4 爹 dao的包扫描-->
<jpa:repositories base-package="cn.zf.jpa.dao" transaction-manager-ref="transactionManager" entity-manager-factory-ref="entityManagerFactory"/>
</beans>
5.在src/main/java下创建实体Customer类
package cn.zf.jpa.entity;
import javax.persistence.*;
// jpa的实体类
//配置实体类和数据库表的映射关系
@Entity
@Table(name="cst_customer")
public class Customer {
// 配置主键生成的策略(主键自增
@GeneratedValue(strategy = GenerationType.IDENTITY)
// 配置主键使用的字段
@Id
@Column(name="cust_id")
private long custId;
@Column(name="cust_name")
private String custName;
@Column(name="cust_source")
private String custSource;
@Column(name="cust_industry")
private String custIndustry;
@Column(name="cust_level")
private String custLevel;
@Column(name="cust_address")
private String custAddress;
@Column(name="cust_phone")
private String custPhone;
public long getCustId() {
return custId;
}
public void setCustId(long custId) {
this.custId = custId;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public String getCustSource() {
return custSource;
}
public void setCustSource(String custSource) {
this.custSource = custSource;
}
public String getCustIndustry() {
return custIndustry;
}
public void setCustIndustry(String custIndustry) {
this.custIndustry = custIndustry;
}
public String getCustLevel() {
return custLevel;
}
public void setCustLevel(String custLevel) {
this.custLevel = custLevel;
}
public String getCustAddress() {
return custAddress;
}
public void setCustAddress(String custAddress) {
this.custAddress = custAddress;
}
public String getCustPhone() {
return custPhone;
}
public void setCustPhone(String custPhone) {
this.custPhone = custPhone;
}
@Override
public String toString() {
return "Customer{" +
"custId=" + custId +
", custName='" + custName + '\'' +
", custSource='" + custSource + '\'' +
", custIndustry='" + custIndustry + '\'' +
", custLevel='" + custLevel + '\'' +
", custAddress='" + custAddress + '\'' +
", custPhone='" + custPhone + '\'' +
'}';
}
}
6.在src/main/java下创建Dao(简单CRUD创建接口就可以,继承JpaRepository
package cn.zf.jpa.dao;
import cn.zf.jpa.entity.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* 需要注意的 继承后里面的泛型 第一个是实体类类型 第二个是该类主键的数据类型
*/
public interface CustomerDao extends JpaRepository<Customer,Long> {
}
7.测试,在src/test/java下创建SpringDataJpaTest测试类(简单CRUD
package cn.zf.jpa.test;
import cn.zf.jpa.dao.CustomerDao;
import cn.zf.jpa.entity.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
/**
* 实现简单的CRUD
*/
public class SpringDataJpaTest {
@Autowired
private CustomerDao customerDao;
/*
添加
*/
@Test
public void addCustomer(){
/*//1.初始化spring容器(加载配置文件
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
//2.从容器中获取dao对象
CustomerDao customerDao = applicationContext.getBean(CustomerDao.class);*/
//创建新的对象,并保存
Customer customer = new Customer();
customer.setCustName("火山");
customer.setCustAddress("智利");
//3.调用dao对象的方法 实现crud
customerDao.save(customer);
}
/*
删除
*/
@Test
public void deleteCustomer(){
customerDao.delete(24l);
}
/*
查找一个
*/
@Test
public void updateCustomer(){
Customer customer = customerDao.findOne(23l);
customer.setCustPhone("78946");
customerDao.save(customer);
}
/*
查询所有
*/
@Test
public void findAllCustomer(){
List<Customer> customerList = customerDao.findAll();
for (Customer customer : customerList) {
System.out.println(customer);
}
}
}
8.测试,在src/test/java下创建SpringDataJpaFindTest测试类(查询
注:使用jpql查询,需要在dao 接口中定义一个方法,使用方法的参数设置jpql 参数,使用返回值接受查询结果,在方法上添加注解@Query注解,并且需要在注解上写spql 语句,在方法上添加注解@Query注解,并且需要在注解上写jpql语句
8.1 Dao接口代码:
package cn.zf.jpa.dao;
import cn.zf.jpa.entity.Customer;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 需要注意的 继承后里面的泛型 第一个是实体类类型 第二个是该类主键的数据类型
*/
public interface CustomerDao extends JpaRepository<Customer,Long> {
//jpql查询
//查询所有(未分页
@Query("from Customer")
List<Customer> getAllCustomer();
//查询所有(分页,需要传入分页参数Pageable 注:org.springframework.data.domain.Pageable下的
@Query("from Customer")
List<Customer> getAllCustomerByPage(Pageable pageable);
//根据id查询
@Query("from Customer where custId=?")
Customer findByIdCustomer(Long id);
//根据字段查询,name模糊查询(多个字段模糊查询使用and
@Query("from Customer where custName like ?")
List<Customer> findByNameLike(String name);
//更新操作
@Modifying
@Transactional
@Query("update Customer set custSource=? where custId=?")
void updateCustomer(String source,Long id);
}
8.2 测试类代码:
package cn.zf.jpa.test;
import cn.zf.jpa.dao.CustomerDao;
import cn.zf.jpa.entity.Customer;
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.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 SpringDataJpaFindTest {
@Autowired
private CustomerDao customerDao;
/*
查询单个(使用findOne方法
*/
@Test
public void findOneCustomer(){
Customer customer = customerDao.findOne(23l);
System.out.println(customer);
}
/*
查询单个(使用getOne方法
*/
@Test
@Transactional
public void getOneCustomer(){
Customer customer = customerDao.getOne(23l);
System.out.println(customer);
}
/*
查询所有(未分页
*/
@Test
public void findAllCustomer(){
List<Customer> customerList = customerDao.findAll();
for (Customer customer : customerList) {
System.out.println(customer);
}
}
/*
查询所有(分页,页码从0开始
*/
@Test
public void findAllByPageCustomer(){
//第一个参数:页码 第二个参数:每页显示条数
PageRequest pageRequest = new PageRequest(0, 5);
Page<Customer> customerPage = customerDao.findAll(pageRequest);
long totalElements = customerPage.getTotalElements();
System.out.println("总记录数为:"+totalElements);
int totalPages = customerPage.getTotalPages();
System.out.println("总页码为:"+totalPages);
for (Customer customer : customerPage) {
System.out.println(customer);
}
}
/*
排序
*/
@Test
public void findAllSortCustomer(){
/*
第一个参数:选择降序还是升序(DESC降序,ASC升序
第二个参数:根据custId排序
*/
Sort sort = new Sort(Sort.Direction.DESC,"custId");
List<Customer> customerList = customerDao.findAll(sort);
for (Customer customer : customerList) {
System.out.println(customer);
}
}
/*
判断某记录是否存在
*/
@Test
public void findOneExists(){
//exists方法返回值是布尔值,存在返回true,不存在返回false
boolean exists = customerDao.exists(23l);
System.out.println(exists);
}
/*
查询总记录数
*/
@Test
public void customerCount(){
long count = customerDao.count();
System.out.println(count);
}
/*
下面使用jpql进行查询
*/
/*
查询所有(未分页
*/
@Test
public void getAllCustomer(){
List<Customer> customerList = customerDao.getAllCustomer();
for (Customer customer : customerList) {
System.out.println(customer);
}
}
/*
查询所有(分页,页码从0开始
*/
@Test
public void getAllCustomerByPage(){
List<Customer> customerList = customerDao.getAllCustomerByPage(new PageRequest(0, 5));
for (Customer customer : customerList) {
System.out.println(customer);
}
}
/*
根据id查询
*/
@Test
public void findByIdCustomer(){
Customer idCustomer = customerDao.findByIdCustomer(23l);
System.out.println(idCustomer);
}
/*
根据name字段模糊查询
*/
@Test
public void findByNameLike(){
List<Customer> byNameLike = customerDao.findByNameLike("%山%");
for (Customer customer : byNameLike) {
System.out.println(customer);
}
}
/*
更新操作
*/
@Test
public void updateCustomer(){
customerDao.updateCustomer("西班牙",23l);
}
}
over~