SpringDateJPA

1. SpringDataJPA

1.1 简介

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

1.2 特性

SpringDataJPA简化了数据访问层代码,只需要在dao层中写接口,就具有了一些基本方法。

2. 快速入门

步骤:

  1. 导入坐标

  2. 整合SpringDataJPASpring

    <?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">
    
        <!-- spring和springDataJpa的配置 -->
        <!-- 用springdatajpa的实现 -->
        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="dataSource" ref="datasource" />
            <!-- 实体类扫描的包 -->
            <property name="packagesToScan" value="com.jerry66.pojo"/>
            <!-- 服务提供者 -->
            <property name="persistenceProvider">
                <bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
            </property>
            <!--jpa的供应商适配器 -->
            <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" />
                    <!--是否显示sql -->
                    <property name="showSql" value="true" />
                </bean>
            </property>
            <!-- jpa方言,高级特性 -->
            <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="user" value="root"/>
            <property name="password" value=""/>
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/jpa?characterEncoding=utf-8"/>
        </bean>
    
        <jpa:repositories base-package="com.jerry66.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>
    
        <!-- 声明式事务 -->
    
        <context:component-scan base-package="com.jerry66"/>
    
    </beans>
    
  3. 准备对应的实体类

  4. 编写规范的dao接口:

    1. 创建一个接口并实现:JpaRepositoryJpaSpecificationExecutor
    2. 提供对应的泛型
    /**
     * JpaRepository<实体类类型,主键类型>:用来完成基本CRUD操作
     * JpaSpecificationExecutor<实体类类型>:用于复杂查询(分页等查询操作)
     */
    public interface CustomerDao extends JpaRepository<Customer, Integer>, JpaSpecificationExecutor<Customer {
    }
    
  5. 完成操作

    1. 保存:

      @Autowired
      private CustomerDao custDao;
      
      public void testSave() {
      	Customer cust = new Customer();
          cust.set....;
          custDao.save(cust);
      }
      
    2. 修改:和保存一样用save,加上id即可

    3. 删除:

      public void delete() {
          custDao.delete(1); // 删除主键为1的数据
      }
      
    4. 根据id查询:

      public void testFind() {
          Customer cust = custDao.findOne(1);
      }
      

3. SpringDataJPA原理

dao中什么都没写就可以用很多的方法,这是因为实现了JpaRepositoryJpaSpecificationExecutor两个接口。

但是接口中只有定义,实现时是由JdkDynamicAopProxy生成了一个动态代理对象SimpleJpaRepository,翻看源码可以看到调用了EntityManager对应的方法,所以SpringDataJPA是对JPA进行了封装。

4. 使用JPQL

使用方法:在方法上面标注@Query注解并提供一个jpql语句

public interface CustomerDao extends JpaRepository<Customer, Integer>, JpaSpecificationExecutor<Customer {
    @Query(value="from Customer")
    public List<Customer> findAll();
    
    // ?1代表参数的占位符,其中1对应方法中的参数索引
    @Query(value="from Customer where custName = ?1")
    public Customer findCustomer(String custName);
}

如果使用sql语句而不是jpql语句:

@Query(value="select * from cst_customer", nativeQuery=true)
public void findSql();

5. 方法命名规则查询

根据SpringDataJPA提供的方法命名规则定义方法的名称,就可以完成查询操作:

  1. findBy开头
  2. 条件查询用条件关键字连接
  3. 条件属性首字母大写
public Customer findByCustSource(String custSource);

举例列表:

关键字例子对应的jpql语句
AndfindByLastnameAndFirstnamewhere x.lastname = ? and x.firstname = ?
OrfindByLastnameOrFirstnamewhere x.lastname = ? or x.firstname = ?
BetweenfindByStartDateBetweenwhere x.startDate between ? and ?

其余类似

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值