Spring Data JPA——概述、Spring Data JPA的CRUD操作

目录

  • 一、Spring Data JPA 概述
    • 1、Spring Data JPA 与 JPA和hibernate之间的关系
  • 二、Spring Data JPA入门
  • 三、Spring Data JPA 完成CRUD

一、Spring Data JPA 概述

Spring Data JPA 是 Spring 基于 ORM 框架、JPA 规范的基础上封装的一套JPA应用框架,可使开发者用极简的代码即可实现对数据库的访问和操作。它提供了包括增删改查等在内的常用功能,且易于扩展!学习并使用 Spring Data JPA 可以极大提高开发效率!

Spring Data JPA 让我们解脱了DAO层的操作,基本上所有CRUD都可以依赖于它来实现,在实际的工作工程中,推荐使用Spring Data JPA + ORM(如:hibernate)完成操作,这样在切换不同的ORM框架时提供了极大的方便,同时也使数据库层操作更加简单,方便解耦!

1、Spring Data JPA 与 JPA和hibernate之间的关系

跳转到目录

  • JPA是一套规范,内部是有接口和抽象类组成的。hibernate是一套成熟的ORM框架,而且Hibernate实现了JPA规范,所以也可以称hibernate为JPA的一种实现方式,我们使用JPA的API编程,意味着站在更高的角度上看待问题(面向接口编程)

  • Spring Data JPA是Spring提供的一套对JPA操作更加高级的封装,是在JPA规范下的专门用来进行数据持久化的解决方案。

Spring Data JPA——概述、Spring Data JPA的CRUD操作_第1张图片

二、Spring Data JPA入门

跳转到目录
Spring Data JPA完成客户的基本CRUD操作

1、环境搭建

引入Spring Data JPA的坐标

<properties>
    <spring.version>4.2.4.RELEASEspring.version>
    <hibernate.version>5.0.7.Finalhibernate.version>
    <slf4j.version>1.6.6slf4j.version>
    <log4j.version>1.2.12log4j.version>
    <c3p0.version>0.9.1.2c3p0.version>
    <mysql.version>5.1.6mysql.version>
properties>

<dependencies>
    
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.9version>
        <scope>testscope>
    dependency>
    
    
    <dependency>
        <groupId>org.aspectjgroupId>
        <artifactId>aspectjweaverartifactId>
        <version>1.6.8version>
    dependency>

    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-aopartifactId>
        <version>${spring.version}version>
    dependency>

    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-contextartifactId>
        <version>${spring.version}version>
    dependency>

    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-context-supportartifactId>
        <version>${spring.version}version>
    dependency>

    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-ormartifactId>
        <version>${spring.version}version>
    dependency>

    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-beansartifactId>
        <version>${spring.version}version>
    dependency>

    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-coreartifactId>
        <version>${spring.version}version>
    dependency>
    
    

    
    <dependency>
        <groupId>org.hibernategroupId>
        <artifactId>hibernate-coreartifactId>
        <version>${hibernate.version}version>
    dependency>
    <dependency>
        <groupId>org.hibernategroupId>
        <artifactId>hibernate-entitymanagerartifactId>
        <version>${hibernate.version}version>
    dependency>
    <dependency>
        <groupId>org.hibernategroupId>
        <artifactId>hibernate-validatorartifactId>
        <version>5.2.1.Finalversion>
    dependency>
    

    
    <dependency>
        <groupId>c3p0groupId>
        <artifactId>c3p0artifactId>
        <version>${c3p0.version}version>
    dependency>
    

    
    <dependency>
        <groupId>log4jgroupId>
        <artifactId>log4jartifactId>
        <version>${log4j.version}version>
    dependency>

    <dependency>
        <groupId>org.slf4jgroupId>
        <artifactId>slf4j-apiartifactId>
        <version>${slf4j.version}version>
    dependency>

    <dependency>
        <groupId>org.slf4jgroupId>
        <artifactId>slf4j-log4j12artifactId>
        <version>${slf4j.version}version>
    dependency>
    

    
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>${mysql.version}version>
    dependency>

    <dependency>
        <groupId>org.springframework.datagroupId>
        <artifactId>spring-data-jpaartifactId>
        <version>1.9.0.RELEASEversion>
    dependency>

    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-testartifactId>
        <version>4.2.4.RELEASEversion>
    dependency>
    
    
    <dependency>  
        <groupId>javax.elgroupId>  
        <artifactId>javax.el-apiartifactId>  
        <version>2.2.4version>  
    dependency>  
      
    <dependency>  
        <groupId>org.glassfish.webgroupId>  
        <artifactId>javax.elartifactId>  
        <version>2.2.4version>  
    dependency> 
    
dependencies>

3、Spring整合Spring Data JPA


<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">
	
    

    
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        
        <property name="packagesToScan" value="com.zy.domain"/>
        
        <property name="persistenceProvider">
            <bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
        property>

        
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                
                <property name="generateDdl" value="false"/>
                
                <property name="database" value="MYSQL"/>
                
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
                
                <property name="showSql" value="true"/>
            bean>
        property>

        
        <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
        property>

    bean>

    
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/jpa?useUnicode=true&characterEncoding=UTF-8" />
        <property name="user" value="root" />
        <property name="password" value="1111" />
    bean>

    
    <jpa:repositories base-package="com.zy.dao" transaction-manager-ref="transactionManager"
        entity-manager-factory-ref="entityManagerFactory">
    jpa:repositories>

    
    <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="update*" propagation="REQUIRED"/>
			<tx:method name="delete*" 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>

    
    <context:component-scan base-package="com.zy"/>
    
	
	<aop:config>
		<aop:pointcut id="pointcut" expression="execution(* cn.itcast.service.*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
	aop:config>
	
beans>

4、使用JPA注解配置映射关系

@Entity
@Table(name = "cst_customer")
public class Customer {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="cust_id")
    private Long custId;
    
    @Column(name="cust_address")
    private String custAddress;
    
    @Column(name="cust_industry")
    private String custIndustry;
    
    @Column(name="cust_level")
    private String custLevel;
    
    @Column(name="cust_name")
    private String custName;
    
    @Column(name="cust_phone")
    private String custPhone;
    
    @Column(name="cust_source")
    private String custSource;
    
	// 省略 getter/setter 方法
}

三、Spring Data JPA 完成CRUD

跳转到目录

1、编写符合Spring Data JPA规范的Dao层接口

Spring Data JPA是spring提供的一款对于数据访问层(Dao层)的框架,使用Spring Data JPA,只需要按照框架的规范提供dao接口,不需要实现类就可以完成数据库的增删改查、分页查询等方法的定义,极大的简化了我们的开发过程

在Spring Data JPA中,对于定义符合规范的Dao层接口,我们只需要遵循以下几点就可以了:

1.创建一个Dao层接口,并实现JpaRepositoryJpaSpecificationExecutor
2.提供相应的泛型

/**
 * Description: 客户dao
 *
 * @author zygui
 * @date 2020/5/5 13:45
 */

/**
 * 符合SpringDataJpa的dao层接口规范
 *      JpaRepository<操作的实体类类型,实体类中主键属性的类型>
 *          * 封装了基本CRUD操作
 *      JpaSpecificationExecutor<操作的实体类类型>
 *          * 封装了复杂查询(分页)
 */
public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> 
{
}

这样我们就定义好了一个符合Spring Data JPA规范的Dao层接口

2、完成CRUD操作

/**
 * Description:
 *
 * @author zygui
 * @date 2020/5/5 13:50
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class CustomerDaoTest {

    @Autowired
    private CustomerDao customerDao;

    /**
     * 根据id来查询
     */
    @Test
    public void testFindOne() {
        Customer customer = customerDao.findOne(1L);
        System.out.println(customer);
    }

    /**
     * save : 保存或者更新
     *      根据传递的对象是否存在主键id,
     *      如果没有id主键属性:保存
     *      存在id主键属性,根据id查询数据,更新数据
     */
    @Test
    public void testSave() {
        Customer customer = new Customer();
        customer.setCustName("栗子");
        customer.setCustLevel("vip");
        customer.setCustIndustry("foot");
        customerDao.save(customer);
    }

    @Test
    public void testUpdate() {
        Customer customer = new Customer();
        customer.setCustId(4L);
        customer.setCustName("鸽子1");
        customer.setCustLevel("svip");
        customerDao.save(customer);
    }

    @Test
    public void testDelete() {
        customerDao.delete(3L);
    }

    @Test
    public void testFindAll() {
        List<Customer> list = customerDao.findAll();
        for (Customer customer : list) {
            System.out.println(customer);
        }
    }

    // 查询客户数量
    @Test
    public void testCount() {
        long count = customerDao.count();
        System.out.println(count);
    }

    /**
     * 测试:判断id为4的客户是否存在
     *      1. 可以查询以下id为4的客户
     *          如果值为空,代表不存在,如果不为空,代表存在
     *      2. 判断数据库中id为4的客户的数量
     *          如果数量为0,代表不存在,如果大于0,代表存在
     */
    @Test
    public void testExists() {
        boolean exists = customerDao.exists(4L);
        System.out.println("id为4的客户 是否存在:"+exists);
    }

    /**
     * 根据id从数据库查询
     *      @Transactional : 保证getOne正常运行
     *
     *  findOne:
     *      em.find()           :立即加载
     *  getOne:
     *      em.getReference     :延迟加载
     *      * 返回的是一个客户的动态代理对象
     *      * 什么时候用,什么时候查询
     */
    @Test
    @Transactional
    public void testGetOne() {
        Customer customer = customerDao.getOne(4L);
        System.out.println(customer);
    }

}

你可能感兴趣的:(JPA)