SpringData

整合源码:链接: https://pan.baidu.com/s/1_dDEEJoqaBTfXs2ZWsvKvA 提取码: cp6s(jar包自行寻找)

author:SimpleWu

time: 2018-10-06 20:51

1.SpringData概述

Spring Data是Spring的一个子项目,主要用于简化数据库访问,支持NoSQL和关系数据存储,主要目标是使数据库的访问变得方便快捷。其中,所支持的NoSQL存储有MongoDB (文档数据库)、Neo4j(图形数据库)、Redis(键/值存储)和Hbase(列族数据库),所支持的关系数据存储技术有JDBC和JPA。JPA Spring Data致力于减少数据访问层(DAO)的开发量。开发者唯一要做的是声明持久层的接口和方法,其他交给Spring Data JPA来完成。

2.SpringData实现对数据库的访问

  1. Spring整合JPA
  2. 在Spring配置文件中配置SpringData让 Spring 为声明的接口创建代理对象。配置了 后,Spring 初始化容器时将会扫描 base-package 指定的包目录及其子目录,为继承 Repository 或其子接口的接口创建代理对象,并将代理对象注册为 Spring Bean,业务层便可以通过 Spring 自动封装的特性来直接使用该对象。
  3. 声明持久层的接口,该接口继承 Repository,Repository 是一个标记型接口,它不包含任何方法,如必要,Spring Data 可实现 Repository 其他子接口,其中定义了一些常用的增删改查,以及分页相关的方法。
  4. 在接口中声明需要的方法。Spring Data 将根据给定的策略(具体策略稍后讲解)来为其生成实现代码。

3.SpringData环境搭建

1.导包(Spring,Hibernate,Mysql,ehcache,c3p0,aspect)

2.首先使用Spring整合JPA(见JPA整合案例)

1)db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/jpa
jdbc.user=root
jdbc.password=root

2)applicationContext.xml(copy注意包位置)

<!-- 引入外部资源文件 -->
    <context:property-placeholder location="classpath:db.properties" />
    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}" />
        <property name="password" value="${jdbc.password}" />
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <!-- 队列中的最小连接数 -->
        <property name="minPoolSize" value="15"></property>
        <!-- 队列中的最大连接数 -->
        <property name="maxPoolSize" value="25"></property>
        <!-- 当连接耗尽时创建的连接数 -->
        <property name="acquireIncrement" value="15"></property>
        <!-- 等待时间 -->
        <property name="checkoutTimeout" value="10000"></property>
        <!-- 初始化连接数 -->
        <property name="initialPoolSize" value="20"></property>
        <!-- 最大空闲时间,超出时间连接将被丢弃 -->
        <property name="maxIdleTime" value="20"></property>
        <!-- 每隔60秒检测空闲连接 -->
        <property name="idleConnectionTestPeriod" value="60000"></property>
    </bean>
    <!-- 配置entityManagerFactory -->
    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <!-- 设置数据源 -->
        <property name="dataSource" ref="dataSource" />
        <!-- jpa注解所在的包 -->
        <property name="packagesToScan" value="com.simple.springdata.entitys" />
        <!-- 配置jpa提供商的适配器,可以通过内部bean的方式类配置 -->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>
        </property>
        <!-- 配置JPA的基本属性 -->
        <property name="jpaProperties">
            <!-- 配置jpa基本属性 -->
            <props>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <!-- 配置二级缓存 -->
                <prop key="hibernate.cache.use_second_level_cache">true</prop>
                <prop key="hibernate.cache.region.factory_class">
                    org.hibernate.cache.ehcache.EhCacheRegionFactory
                </prop>
                <prop key="hibernate.cache.use_query_cache">true</prop>
            </props>
        </property>
    </bean>
    <!-- 配置事务管理器 -->
    <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>
    <!-- 配置支持注解的事务 -->
    <tx:annotation-driven transaction-manager="txManager" />
    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="com.simple.springdata">
        <!-- 除了@Controller修饰的全部都要 -->
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

3.在Spring(applicationContext)XML配置下增加SpringDataJPA的支持

​ 1)entity-manager-factory-ref: 引用的是生成EntityManager的工厂

​ 2)transaction-manager-ref:需要对事物管理进行引用

<!-- 5、配置SpringData -->
    <jpa:repositories base-package="com.simple.springdata.dao"
        entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="txManager"></jpa:repositories>

4.添加Dao层接口,这个接口需要实现Repository。Repository是一个泛型接口Repository<要处理的类型,主键类型>。

5.在Dao层定义方法即可,方法是有命名规范的所以说是不能够随便乱写名字。

package com.simple.springdata.service;

import org.springframework.transaction.annotation.Transactional;

import com.simple.springdata.entitys.Employee;

public interface EmployeeService {
    /**
     * 保存员工方法
     */
    @Transactional
    Employee save(Employee employee);
}

这样就已经与我们SpringData已经与我们Spring整合完毕了。

4.继续整合SpringMVC

在上面我们已经对Spring进行了整合,现在我们来继续整合上SpringMVC。

1)创建SpringMVC配置文件
<!-- 扫描所有@Controller注解修饰的类 -->
    <context:component-scan base-package="com.simple.springdata">
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!--将非mapping配置下的请求交给默认的Servlet来处理 -->
    <mvc:default-servlet-handler />
    <!--如果添加了默认servlet,mvc请求将无效,需要添加annotation-driven -->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!-- 配置试图解析器 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
2)配置WEB.XML
<!-- 解决JPA懒加载问题 -->
    <filter>
        <filter-name>OpenEntityManager</filter-name>
        <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>OpenEntityManager</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 添加Spring容器的监听 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 编码过滤器 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <async-supported>true</async-supported>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 启动SpringMVC核心控制器 -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!-- 添加PUT DELETE支持 -->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

5.Repository接口介绍

Repository 接口是 Spring Data 中的一个空接口,它不提供任何方法,我们称为标记接口,可以在接口中声明需要的方法。

public interface Repository<T, ID extends Serializable> { } 若我们定义的接口继承了Repository接口,则该接口会被Spring容器识别为一个Repository类,并纳入到Spring容器中。

Spring Data可以让我们只定义接口,只要遵循 Spring Data的规范,就无需写实现类。

与继承 Repository 等价的一种方式,就是在持久层接口上使用 @RepositoryDefinition 注解,并为其指定 domainClass 和 idClass 属性。

package com.simple.springdata.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.RepositoryDefinition;

import com.simple.springdata.entitys.Dept;

/**
 * @author SimpleWu
 * @RepositoryDefinition(domainClass=Dept.class,idClass=Integer.class)与继承
 * JpaRepository<Dept, Integer>效果一致
 */
@RepositoryDefinition(domainClass=Dept.class,idClass=Integer.class)
public interface DeptDao /*extends JpaRepository<Dept, Integer>*/{

}

6.Repository 的子接口

基础的 Repository 提供了最基本的数据访问功能,其几个子接口则扩展了一些功能。它们的继承关系如下:

Repository: 仅仅是一个标识,表明任何继承它的均为仓库接口类

1)CrudRepository: 继承 Repository,实现了一组 CRUD 相关的方法

2)PagingAndSortingRepository: 继承 CrudRepository,实现了一组分页排序相关的方法 

3)JpaRepository: 继承 PagingAndSortingRepository,实现一组 JPA 规范相关的方法 自定义的 5)XxxxRepository 需要继承 JpaRepository,这样的 XxxxRepository 接口就具备了通用的数据访问控制层的能力。4)JpaSpecificationExecutor: 不属于Repository体系,实现一组 JPA Criteria 查询相关的方法 

7.SpringData方法定义规范

在SpringData的Repository 接口中的方法必须满足一定的规则。

按照 Spring Data 的规范,查询方法以 find | read | get 开头,涉及条件查询时,条件的属性用条件关键字连接,要注意的是:条件属性以首字母大写。 

public Employee getByLastNameAndGender(String lastName,String gender)

这个接口中需要处理的类型Employee,在这个类中必须有个属性叫做LastName与gender,And是条件连接

条件的属性名称与个数要与参数的位置与个数一一对应

SpringData使用与整合-LMLPHP

SpringData使用与整合-LMLPHP

8.@Query注解

使用这个注解可以摆脱在Reponsitory接口中方法命名的规范,我们将查询的语句直接生命在方法上

1)索引

查询中 “?X” 个数需要与方法定义的参数个数相一致,并且顺序也要一致

@Query("select d from Dept d where dno = ?1 and deptName = ?2")
    public Dept testQuery(Integer dno,String deptName);
2)命名查询
@Query("select d from Dept d where dno = :dno and deptName = :deptName")
    public Dept testQuery(@Param("dno")Integer dno,@Param("deptName")String deptName);

9.本地SQL查询

在注解@Query中有个参数nativeQuery将他设置为true即可开启本地SQL查询

@Query(value="select * from tal_dept",nativeQuery=true)
    public List<Dept> testQuery3();
注意事项

前面我们基本都是在执行查询操作,@Query也可以做修改和删除的操作,但不支持增加。执行修改操作时,必须使用@Modifying注解。

@Modifyingjava
@Query("UPDATE tal_dept set name = :name WHERE dno = :dno")
public int updateTest(@Param("dno")Integer id,@Param("name")String name);
10-06 21:45