SpringDataJpa(三) springDataJpa 概述及入门操作

SpringData JPA(三) springDataJpa 概述及入门操作

1.SpringData Jpa 概述

Spring Data JPA 是Spring基于ORM思想,在JPA规范的基础上封装的一套JPA应用框架,是Spring提供的一套对JPA操作更加高级的封装,是在JPA规范下的专门用来进行数据持久化的解决方案。

可使开发者用极简的代码即可实现对数据库的访问和操作。它提供了包括增删改查等在内的常用功能,且易于扩展!学习并使用 Spring Data JPA 可以极大提高开发效率!

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8Ekp93oP-1582016046659)(./01-springDataJpa,jpa,hibernate关系.png)]

2.SpringData Jpa 入门操作

1.创建Maven工程,导入依赖
2.配置Spring配置文件(配置SpringData 整合)
3.编写实体类,配置实体与表的映射关系
4.编写Dao层接口,继承JpaRepository,JpaSpecificationExecutor两接口

1)创建Maven工程,导入依赖
  <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>
    </properties>

    <dependencies>
        <!-- junit单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
            <scope>test</scope>
        </dependency>

        <!-- spring beg -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</version>
        </dependency>

        <!--aop-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--ioc-->
        <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-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--核心包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--spring orm 框架支持包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--spring单元测试整合包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</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>


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

2)配置Spring配置文件(配置SpringData 整合)

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///jpa
jdbc.username=root
jdbc.password=123456

applicationContext.xml

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

       <!--引入外部配置文件-->
       <context:property-placeholder location="classpath*:jdbc.properties"/>

       <!--1.
           将entityManagerFactory 交给spring管理
           LocalContainerEntityManagerFactoryBean
              class:LocalContainerEntityManagerFactoryBean  EntityManagerFactory接口 的实现类
        -->
       <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">

           <!--注入数据源-->
           <property name="dataSource" ref="dataSource"/>
           <!--设置扫描包(实体类所在的包)-->
           <property name="packagesToScan" value="com.xx.entity"/>

           <!--设置jpa 的实现厂家-->
           <property name="persistenceProvider">
               <bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
           </property>

           <!--jpa供应商适配器-->
           <property name="jpaVendorAdapter">
               <!--Hibernate 供应商-->
               <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                   <!--连接数据库:MySQL-->
                   <property name="database" value="MYSQL"/>
                   <!--是否自动创建数据库表-->
                   <property name="generateDdl" value="false"/>
                   <!--配置数据库方言 支持该数据库的所有语法-->
                   <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
                   <!--是否打印sql语句-->
                   <property name="showSql" value="true"/>
               </bean>
           </property>

           <!--配置jpa方言-->
           <property name="jpaDialect">
               <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
           </property>
       </bean>

        <!--2.整合springData jpa
                base-package:dao接口所在包
                entity-manager-factory-ref:实体管理器
                transaction-manager-ref:事务管理器
        -->
       <jpa:repositories base-package="com.xx.dao" entity-manager-factory-ref="entityManagerFactory"
                         transaction-manager-ref="transactionManager">

       </jpa:repositories>

       <!--3.配置数据源-->
       <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
           <property name="driverClass" value="${jdbc.driver}"/>
           <property name="jdbcUrl" value="${jdbc.url}"/>
           <property name="user" value="${jdbc.username}"/>
           <property name="password" value="${jdbc.password}"/>
       </bean>

      <!--4.配置事务管理器-->
      <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
           <!--注入工厂-->
           <property name="entityManagerFactory" ref="entityManagerFactory"/>
      </bean>

      <!--5.声明式事务-->
      <tx:advice id="txAdvice" transaction-manager="transactionManager">

          <!--
             REQUIRED: 必须让当前业务在事务的管理下,
              如果没有事务就自动创建事务,如果又事务就是用当前事务
             SUPPORTS: 事务可有可无,没有事务就不使用,有就使用

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

      <!--6.配置包扫描-->
      <context:component-scan base-package="com.xx"/>


</beans>
3)编写实体类
   
/**
 *  客户实体类
 */
Entity
@Table(name = "t_cst_customer")
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "cust_id")
    private Long custId;
    @Column(name = "cust_name")
    private String custName;
    @Column(name = "cust_industry")
    private String custIndustry;
    @Column(name = "cust_source")
    private String custSource;
    @Column(name = "cust_level")
    private String custLevel;
    @Column(name = "cust_address")
    private String custAddress;
    @Column(name = "cust_phone")
    private String custPhone;

4)简单查询

三种查询方式

  • jpa api
  • jpql/sql 查询
    • @Query(nativeQuery=, value="")
    • nativeQuery=true sql查询
    • nativeQuery=false jqpl查询
    • value="" 查询语句
  • 命名规则查询
    • 精准查询findBy+实体属性名称
      eg: findByCustName====> from 实体类名 where custName = ?
    • 模糊查询…find+实体属性名称+查询方式(like|isNUll)
      eg: findByCustNameLike====> from 实体类名 where custName like ?
    • 多条件查询: find + 实体属性名称 + 查询方式 + 连接符号(And|Or) 实体属性名称 + 查询方式…
      eg: findByCustNameLikeAndCustIndustry ==> from 实体类名 where custName like ? and custIndustry = ?
4_v1_jpa api
4_v1_v1_Dao层
/**
 *  Customer 持久层接口
 *    继承两个接口,提供相应的泛型
 *       JpaRepository<要操作实体类的类型, 主键属性类型>
 *           封装了基础CRUD操作
 *       JpaSpecificationExecutor<要操作的实体类的类型>
 *           封装了复杂查询
 */
public interface CustomerDao extends JpaRepository<Customer, Long> , JpaSpecificationExecutor<Customer>{
}
4_v1_v2_测试类
@RunWith(SpringJUnit4ClassRunner.class) //声明spring测试
@ContextConfiguration(locations = "classpath*:applicationContext.xml") //加载配置文件
public class test01 {

    @Autowired
    CustomerDao customerDao;

     /**
     *  根据id 查询指定客户
     *      findOne:立即加载
     *         find()
     *      getOne:延迟加载
     *         getReference  返回的是实体类的动态代理对象,什么时候使用,什么时候查询
     */
    @Test
    public void test_findOne(){
        Customer customer = customerDao.findOne(3l);
        System.out.println(customer);
    }
    @Test
    @Transactional  //使得方法测试顺利进行
    public void test_getOne(){
        Customer customer = customerDao.getOne(3l);
        System.out.println(customer);
    }

    /**
     *     save()   保存/跟新客户
     *        如果不存在主键属性,执行保存操作
     *        如果存在主键属性,纤维根据主键查询数据库,再更新各值,
     *                      如果根据id无法查询出数据,则执行插入操作(主键依据主键生成策略生成)
     */
    @Test
    public void test_save(){
        Customer customer = new Customer();
        //customer.setCustId(8l);
        customer.setCustName("张三集团");
        customer.setCustLevel("vip");
        customerDao.save(customer);
    }

    /**
     * 先查询后更新
     */
    @Test
    public void test_update(){
        Customer customer = customerDao.findOne(5l);
        //customer.setCustId(8l);
        customer.setCustIndustry("网络推荐");
        customer.setCustAddress("北上广");
        customerDao.save(customer);
    }

    /**
     * 删除测试
     *    根据id删除记录
     *      先查询记录是否存在,如果存在就删除,不存在就报错
     */
    @Test
    public void test_delete(){
        customerDao.delete(8l);
    }

    /**
     * 查询所有
     */
    @Test
    public void test_findAll(){
        List<Customer> list = customerDao.findAll();
        for (Customer customer : list) {
            System.out.println(customer);
        }
    }
    
     /**
     *  统计查询
     */
    @Test
    public void test_count(){
        long count = customerDao.count();
        System.out.println(count);
    }

    /**
     *  判断指定id的客户是否存在,如果存在返回true,不存在返回false
     */
    @Test
    public void test_exists(){
        boolean exists = customerDao.exists(4l);
        System.out.println(exists);
    }
}

4_v2_jqpl简单使用:
  • @Query(nativeQuery=, value="")
  • nativeQuery=true sql查询
  • nativeQuery=false jqpl查询
  • value="" 查询语句
4_v2_v1_Dao层
public interface CustomerDao extends JpaRepository<Customer, Long> , JpaSpecificationExecutor<Customer>{

    /**
     * jpql查询
     *    根据名称查询客户信息
     * @Query
     */
     @Query(value = "from Customer where custName = ?1")
     public Customer findByName(String custName);

    /**
     *  根据名称和id查询客户信息
     *     默认情况下:
     *           占位符的位置要与方法参数的位置一致
     *     非默认情况下:
     *           要在占位符后添加索引,指定该占位符从哪个参数获取值
     */
     @Query(value = "from Customer where custName = ?2 and custId = ?1")
     public Customer findByNameAndId(Long id,String name);

    /**
     *  更新操作
     *     @Modifying: 当前执行的是一个更新操作
     *       返回值是影响记录的行数
     */
     @Query(value = "update Customer set custName = ?2 where custId = ?1")
     @Modifying
     public Integer updateName(Long id, String name);

    /**
     * 查询全部
     *    nativeQuery: 本地查询,默认是nativeQuery=false
     *       true: 使用sql语句查询
     *       false: 使用jpql 语句查询
     */
     @Query(nativeQuery = true, value = "select * from t_cst_customer")
     public List<Object[]> findAllBySql();

    /**
     * sql 模糊查询
     */
    @Query(nativeQuery = true, value = "select * from t_cst_customer where cust_name like ?1")
    public List<Object[]> findAllByLike(String name);
}
4_v2_v2_测试类
  @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:applicationContext.xml")
public class JpqlTest {

    @Autowired
    private CustomerDao customerDao;

    /**
     * 根据名称查询客户
     */
    @Test
    public void test_findByName(){
        Customer customer = customerDao.findByName("666");
        System.out.println(customer);
    }

    /**
     * 根据名称和id查询客户
     */
    @Test
    public void test_findByNameAndId(){
        //Customer customer = customerDao.findByNameAndId("777", 4l);
        Customer customer = customerDao.findByNameAndId(4l,"777");
        System.out.println(customer);
    }

    /**
     * 根据id更新名称
     *      @Transactional: 更新/删除操作
     *         需要手动添加事务支持
     *      @Rollback: 默认事务自动回滚
     *             true|false
     */
    @Test
    @Transactional  //添加事务支持
    @Rollback(value = false)
    public void test_updateName(){
        Integer lin = customerDao.updateName(8l, "777");
        System.out.println(lin);
    }

    /**
     * sql 查询全部
     */
    @Test
    public void test_findAllBySql(){
        List<Object[]> allBySql = customerDao.findAllBySql();
        for (Object[] objects : allBySql) {
            System.out.println(Arrays.toString(objects));
        }
    }

    /**
     * sql 模糊查询全部
     */
    @Test
    public void test_findAllByLike(){
        List<Object[]> allBySql = customerDao.findAllByLike("%三%");
        for (Object[] objects : allBySql) {
            System.out.println(Arrays.toString(objects));
        }
    }

}

4_v3_命名规则查询
  • 精准查询findBy+实体属性名称
    eg: findByCustName====> from 实体类名 where custName = ?
  • 模糊查询…find+实体属性名称+查询方式(like|isNUll)
    eg: findByCustNameLike====> from 实体类名 where custName like ?
  • 多条件查询: find + 实体属性名称 + 查询方式 + 连接符号(And|Or) 实体属性名称 + 查询方式…
    eg: findByCustNameLikeAndCustIndustry ==> from 实体类名 where custName like ? and custIndustry = ?
4_v3_v1_Dao层
public interface CustomerDao extends JpaRepository<Customer, Long> , JpaSpecificationExecutor<Customer>{

    /**
     *  命名规则查询
     *     findBy实体属性名称: 查询  属性名称首字母大写
     *        属性名称会被当作条件
     *        eg:  findByCustName ===> from Customer  where custName = ?
     *
     *     findBy + 实体属性名称   精准查询
     *     findBy + 实体属性名称 + 查询方式(like | is noll)
     *     多条件查询: 方法参数顺序要一致
     *     findBy + 实体属性名称 + 查询方式 + 条件连接符(And|Or) + 实体属性名称 + 查询方式...
     */
    public Customer findByCustName(String custName);


    /**
     * 命名规则模糊查询
     */
    public List<Customer> findByCustNameLike(String custName);

    /**
     * 命名规则多条件查询
     */
    public  List<Customer> findByCustNameLikeAndCustIndustry(String custName, String custIndustry);
}

4_v3_v2_测试类
 @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:applicationContext.xml")
public class JpqlTest {

    @Autowired
    private CustomerDao customerDao;
    /**
     *  命名规则查询
     *    条件查询
     */
    @Test
    public void test_nameing(){
        Customer customer = customerDao.findByName("张三1");
        System.out.println(customer);
    }

    /**
     *  命名规则模糊查询
     *
     */
    @Test
    public void test_like(){
        List<Customer> list = customerDao.findByCustNameLike("%三%");
        for (Customer customer : list) {
            System.out.println(customer);
        }
    }


    /**
     *  命名规则多条件查询
     *
     */
    @Test
    public void test_ManyConditions(){
        List<Customer> list = customerDao.findByCustNameLikeAndCustIndustry("%三%","网络推荐");
        for (Customer customer : list) {
            System.out.println(customer);
        }
    }
}

发布了47 篇原创文章 · 获赞 7 · 访问量 2333

猜你喜欢

转载自blog.csdn.net/qq_43616898/article/details/104370391