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是条件连接

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

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

SpringData使用与整合的更多相关文章

  1. JPA和SpringData知识梳理

    一. JPA,全称Java Persistence API,用于对象持久化的API,定义一套接口,来规范众多的ORM框架,所以它是在ORM框架之上的应用. 下面主要讲JPA在Hibernate基础上的 ...

  2. Spring全家桶相关文章汇总(Spring,SpringBoot,SpringData,SpringCloud)

      因为Spring框架包含的组件比较多,写的博客内容也比较多,虽然有分专栏但是依然不方便查找,所以专门用一篇文章来记录相关文章,会不定期更新. 一.Spring 1.基础内容 Spring介绍 Sp ...

  3. 带着萌新看springboot源码11(springboot启动原理 源码上)

    通过前面这么多讲解,springboot原理应该也大概有个轮廓了,一些基本的配置,从客户端url到controller(配置一些要用的组件,servlet三大组件,处理器映射器,拦截器,视图解析器这些 ...

  4. ElasticSearch实战系列三: ElasticSearch的JAVA API使用教程

    前言 在上一篇中介绍了ElasticSearch实战系列二: ElasticSearch的DSL语句使用教程---图文详解,本篇文章就来讲解下 ElasticSearch 6.x官方Java API的 ...

  5. Spring、SpringMVC、SpringData + JPA 整合详解

    原创播客,如需转载请注明出处.原文地址:http://www.cnblogs.com/crawl/p/7759874.html ------------------------------------ ...

  6. SpringBoot+SpringData 整合入门

    SpringData概述 SpringData :Spring的一个子项目.用于简化数据库访问,支持NoSQL和关系数据存储.其主要目标是使用数据库的访问变得方便快捷. SpringData 项目所支 ...

  7. 【串线篇】spring boot整合SpringData JPA

    一.SpringData简介 其中SpringData JPA底层基于hibernate 二.整合SpringData JPA JPA: Java Persistence API的简称,中文名Java ...

  8. springdata整合mongodb一些方法包括or,and,regex等等《有待更新》

    这几天接触mongodb以及springdata,自己英语比较戳,所以整理这些方法花的时间多了点,不过也是我第一次在外国网站整理技术 不多说,直接上代码,这里只是给出一些操作方法而已,如果有需要源码的 ...

  9. SpringBoot整合SpringData JPA入门到入坟

    首先创建一个SpringBoot项目,目录结构如下: 在pom.xml中添加jpa依赖,其它所需依赖自行添加 <dependency> <groupId>org.springf ...

随机推荐

  1. 简单SQL语句

    一.基础 模式定义了数据如何存储.存储什么样的数据以及数据如何分解等信息,数据库和表都有模式. 主键的值不允许修改,也不允许复用(不能使用已经删除的主键值赋给新数据行的主键). SQL 语句不区分大小 ...

  2. nnet3中的数据类型

    目标与背景 之前的nnet1和nnet2基于Component对象,是一个组件的堆栈.每个组件对应一个神经网络层,为简便起见,将一个仿射变换后接一个非线性表示为一层网络,因此每层网络有两个组件.这些旧 ...

  3. 事件对象event

    每个事件都有默认事件event对象 e.target 事件目标对象 e.keycode 键码 e.stopPropogation();//阻止默认事件

  4. 剑指Offer-把数组排成最小的数

    题目描述 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个.例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323. 思路 可以看 ...

  5. react-踩坑记录——Link带参数跳转后this.props为空对象

    原因,自组件在挂载时,父组件没向其传props划线部分不可缺少!!!!!!

  6. 执行maven install跳过执行maven test方法(网上搜的记录一下,方面以后使用)

    直接在pom文件加上这段配置就可以了 <plugin>           <groupId>org.apache.maven.plugins</groupId>  ...

  7. python基本数据结构栈stack和队列queue

    1,栈,后进先出,多用于反转 Python里面实现栈,就是把list包装成一个类,再添加一些方法作为栈的基本操作. 栈的实现: class Stack(object): #初始化栈为空列表 def _ ...

  8. w10谷歌chrome关闭自动更新

    运行输入:msconfig打开服务 选择服务,找到谷歌更新 ,点击禁用  ,然后保存 保存会要求重启电脑 ,重启后打开页面谷歌  ,会出现弹窗,是否更新 ,点否 . 然后解决,不会再自动更新了. 这是 ...

  9. Django中的缓存基础知识

    由于Django是动态网站,所有每次请求均会去数据进行相应的操作,当程序访问量大时,耗时必然会更加明显,最简单解决方式是使用:缓存,缓存将一个某个views的返回值保存至内存或者memcache中,5 ...

  10. 使用ENCKEYS方法加密数据

    要使用这种数据加密方法,您需要配置Oracle GoldenGate以生成加密密钥并将密钥存储在本地ENCKEYS文件中.此方法使用的永久密钥只能通过根据使用加密密钥填充ENCKEYS文件中的说明重新 ...