SpringData JPA 入门

1. 概述

Spring Data 项目的目的是为了简化构建基于 Spring 框架应用的数据访问技术,包括非关系数据库、Map-Reduce 框架、云数据服务等等;另外也包含对关系数据库的访问支持。

Spring Data 包含多个子项目:

  • Commons - 提供共享的基础框架,适合各个子项目使用,支持跨数据库持久化

  • Hadoop - 基于 Spring 的 Hadoop 作业配置和一个 POJO 编程模型的 MapReduce 作业

  • Key-Value - 集成了 Redis 和 Riak,提供多个常用场景下的简单封装

  • Document - 集成文档数据库:CouchDB 和 MongoDB 并提供基本的配置映射和资料库支持

  • Graph - 集成 Neo4j 提供强大的基于 POJO 的编程模型

  • Graph Roo AddOn - Roo support for Neo4j

  • JDBC Extensions - 支持 Oracle RAD、高级队列和高级数据类型

  • JPA - 简化创建 JPA 数据访问层和跨存储的持久层功能

  • Mapping - 基于 Grails 的提供对象映射框架,支持不同的数据库

  • Examples - 示例程序、文档和图数据库

  • Guidance - 高级文档
    其实Spring Data项目旨在提供一种通用的编码模式,统一持久化操作的封装,简化数据库操作。

2.SpringData JPA 快速入门

  • 配置 SpringData Jpa 的依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.xingxue.s2sp</groupId>
  <artifactId>s2sp</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>

  <dependencies>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.3.5.Final</version>
    </dependency>
    <!-- 整合 JPA 的依赖包 -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>4.3.5.Final</version>
    </dependency>
    <!--Spring 相关的依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.0.4.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>4.0.4.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>4.0.4.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.0.4.RELEASE</version>
    </dependency>
    <!-- 关键 orm 模块的包 整合 hibernate 依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.0.4.RELEASE</version>
    </dependency>

    <!-- spring 整合 struts2 配置 web 模块-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.0.4.RELEASE</version>
    </dependency>


    <!-- struts2 相关的依赖-->
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-core</artifactId>
      <version>2.5.14.1</version>
    </dependency>

    <!--提供一个 struts2 整合 Spring 的整合插件-->
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-spring-plugin</artifactId>
      <version>2.5.14.1</version>
    </dependency>


    <!--添加 springdatajpa 的依赖-->
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-jpa</artifactId>
      <version>1.5.3.RELEASE</version>
    </dependency>



    <!-- 其他可选依赖-->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>

    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc14</artifactId>
      <version>10.2.0</version>
      <scope>runtime</scope>
    </dependency>

    <!-- servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>
    <!-- jsp-api -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.2.1</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>

    <plugins>
      <plugin>

        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <path>/</path>
          <port>80</port>
        </configuration>
      </plugin>
    </plugins>



    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.xml</include>
          <include>**/*.properties</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
  </build>



</project>

  • Spring 配置文件
<?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:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <context:component-scan base-package="com.xingxue"/>

    <context:property-placeholder location="classpath:jdbc.properties"/>


    <util:properties id="hibernatePro">
        <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
        <prop key="hibernate.show_sql">true</prop>
        <prop key="hibernate.format_sql">true</prop>
    </util:properties>

    <!--spring 提供了一个 LocalContainerEntityManagerFactoryBean 来完成 entityManagerFactory 对象创建,并把该对象纳入 容器 管理-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
          p:dataSource-ref="dataSource"
          p:packagesToScan="com.xingxue.s2sh.domain"
          p:jpaProperties-ref="hibernatePro"
          p:jpaVendorAdapter-ref="jpaVendorAdapter"
    />

    <!--配置 jpa 的实现 为Hibernate-->
    <bean id="jpaVendorAdapter"
          class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    </bean>


    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          p:url="${jdbc.url}"
          p:driverClassName="${jdbc.driver}"
          p:username="${jdbc.user}"
          p:password="${jdbc.password}"
    />

    <!--配置 spring 事务切面类-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
         p:entityManagerFactory-ref="entityManagerFactory"
    />
    <!--开启事务注解驱动-->
    <tx:annotation-driven/>

    <!-- springdata 去数据访问层扫接口,完成接口的代理实现类生成,并创建相应的对象,并纳入spring 容器管理-->
    <jpa:repositories base-package="com.xingxue.s2sh.dao" 
                      entity-manager-factory-ref="entityManagerFactory" 
                      transaction-manager-ref="transactionManager"/>


</beans>
  • 接口的定义
public interface IUserDao extends Repository<User,Long> {

3.Repository 接口规范

  • 接口结构图


    图片.png
  • Repository<Object,Serializable>(父接口):
    该接口是一个标识接口(没有任何常量和方法),作用打个标记,方便SpringData Jpa 功能识别。
    Object:操作的实体
    Serializable:实体的主键类型
    SpringData 提出了约定优于编码的编程思想,所有定义了大量自定义方法的规范。
    findBy、getBy、Like、And 关键字,是帮助安装规则去查询,这样的关键子如表所示:

关键字 示例 同功能 JPQL
And findByLastnameAndFirstname where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname where x.lastname = ?1 or x.firstname = ?2
Is,Equals findByFirstname,findByFirstnameIs,findByFirstnameEqual where x.firstname = 1?
Between findByStartDateBetween where x.startDate between 1? and ?2
LessThan findByAgeLessThan where x.age < ?1
LessThanEqual findByAgeLessThanEqual where x.age = ?1
GreaterThan findByAgeGreaterThan where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual where x.age >= ?1
After findByStartDateAfter where x.startDate > ?1
Before findByStartDateBefore where x.startDate < ?1
IsNull findByAgeIsNull where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull where x.age not null
Like findByFirstnameLike where x.firstname like ?1
NotLike findByFirstnameNotLike where x.firstname not like ?1
StartingWith findByFirstnameStartingWith where x.firstname like ?1 (parameter bound with appended %)
EndingWith findByFirstnameEndingWith where x.firstname like ?1 (parameter bound with prepended %)
Containing findByFirstnameContaining where x.firstname like ?1 (parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc where x.age = ?1 order by x.lastname desc
Not findByLastnameNot where x.lastname <> ?1
In findByAgeIn(Collection ages) where x.age in ?1
NotIn findByAgeNotIn(Collection age) where x.age not in ?1
True findByActiveTrue() where x.active = true
False findByActiveFalse() where x.active = false
IgnoreCase findByFirstnameIgnoreCase where UPPER(x.firstame) = UPPER(?1)
  • CrudRepository<Object,Serializable>
    抽取了10个最基本常用方法(find 查询、delete 删除、save 添加操作),也多写个 crud 字母,可以获得10个方法。何乐而不为!

  • PagingAndSortingRepository<Object,Serializable> 带分页和排序的功能
    三个分页排序功能的类型:

    • Page:分页查询出来的封装模型
    • Pageable:分页使用的页码和大小 当前页码和页面大小
    • Sort:做排序的
      该接口不建议使用,一般在定义方法的时候,把pageable 类对象和 Sort 类型对象传入进去就行了。
  • JpaRepository<Object,Serializable>
    略过,添加两个操作 JPA 的方法。

4.支持 @Query 自定义 JPQL 查询 略过...

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容