集成SpringDataJpa,并测试crud以及分页,排序

一.什么是SpringDataJpa

  • 它是JPA规范的再次封装抽象,底层还是使用了Hibernate的JPA技术实现,引用JPQL的查询语句 ,是属于Spring的生成体系中的一部分.
  • 集成Jpa,让咱们操作数据库变得更加的简单

二.项目导包 pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>cn.itsource</groupId>
  <artifactId>aisell</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>aisell Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <org.springframework.version>4.2.5.RELEASE</org.springframework.version>
    <org.hibernate.version>4.3.8.Final</org.hibernate.version>
    <spring-data-jpa.version>1.9.0.RELEASE</spring-data-jpa.version>
    <com.fasterxml.jackson.version>2.5.0</com.fasterxml.jackson.version>
    <org.slf4j.version>1.6.1</org.slf4j.version>
  </properties>
  <dependencies>
    <!-- Spring的支持包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <!-- 上下文支持包(帮我们集成:模板,邮件,任务调度...) -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${org.springframework.version}</version>
      <scope>test</scope>
    </dependency>
    <!-- 引入web前端的支持 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <!-- SpringMCV上传需要用到io包-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-io</artifactId>
      <version>1.3.2</version>
    </dependency>
    <!-- 文件上传用到的包 -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.2.2</version>
    </dependency>
    <!-- SpringMVC的json支持包 -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>${com.fasterxml.jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>${com.fasterxml.jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${com.fasterxml.jackson.version}</version>
    </dependency>
    <!-- hibernate的支持包 -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>${org.hibernate.version}</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>${org.hibernate.version}</version>
    </dependency>
    <!-- SpringDataJpa的支持包 -->
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-jpa</artifactId>
      <version>${spring-data-jpa.version}</version>
    </dependency>
    <!-- SpringData的擴展包 -->
    <dependency>
      <groupId>com.github.wenhao</groupId>
      <artifactId>jpa-spec</artifactId>
      <version>3.1.1</version>
      <!-- 把所有的依賴都去掉 -->
      <exclusions>
        <exclusion>
          <groupId>*</groupId>
          <artifactId>*</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.2.2</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.6</version>
    </dependency>
    <!--lang3:工具包 java.lang.-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.5</version>
    </dependency>
    <!-- 測試包 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <!-- 这个scope 只能作用在编译和测试时,同时没有传递性。表示在运行的时候不添加此jar文件 -->
      <scope>provided</scope>
    </dependency>
    <!-- 日志文件 -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${org.slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${org.slf4j.version}</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.14</version>
    </dependency>
    <!-- 代码生成器模版技术  -->
    <dependency>
      <groupId>org.apache.velocity</groupId>
      <artifactId>velocity</artifactId>
      <version>1.6</version>
    </dependency>
    <!-- shiro(权限框架)的支持包 -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-all</artifactId>
      <version>1.4.0</version>
      <type>pom</type>
    </dependency>
    <!-- shiro与Spring的集成包 -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-spring</artifactId>
      <version>1.4.0</version>
    </dependency>
    <!-- poi(操作办公软件)支持的jar包 -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.11</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>3.11</version>
    </dependency>
    <!-- 图片压缩功能 -->
    <!-- 缩略图 -->
    <dependency>
      <groupId>net.coobird</groupId>
      <artifactId>thumbnailator</artifactId>
      <version>0.4.6</version>
    </dependency>
    <!-- 定时调度 -->
    <dependency>
      <groupId>quartz</groupId>
      <artifactId>quartz</artifactId>
      <version>1.5.2</version>
    </dependency>
    <!-- 邮件支持 -->
    <dependency>
      <groupId>javax.mail</groupId>
      <artifactId>mail</artifactId>
      <version>1.4.1</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>aisell</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>8.1.15.v20140411</version>
        <configuration>
          <stopPort>9966</stopPort>
          <stopKey>foo</stopKey>
          <webAppConfig>
            <contextPath>/</contextPath>
          </webAppConfig>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

三 集成SpringDataJpa

3.1 完成Spring与Jpa的集成

3.1.1 准备jdbc.propeties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///yxb
jdbc.username=root
jdbc.password=123456

3.2.2 准备applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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
">
    <!--扫描service层的类-->
    <context:component-scan base-package="cn.itsource.aisell.service" />
    <!--
        db.properties -> dataSource(配置数据源[连接池dbcp]) -> EntityManagerFactory -> dao -> service
            -> 事务 -> controller(集成SpringMVC) -> easyui
    -->
    <!--1.读取db.properties, 注意:不要忘了加classpath-->
    <context:property-placeholder location="classpath:jdbc.properties" />
    <!--2.配置dbcp连接池-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
    <!--
        JPA:ORM规范  -> 很多框架实现了这个规范(hibernate,openjpa,toplink,...)
        3.配置EntityManagerFactory对象
            3.1 基本配置都是写在Spring中(四大金刚,建表策略,方言,是否显示SQL)
            3.2 Spring来创建这个对象(准备一个domain,如果运行的时候创建了表,就代表这个对象是成功的)
            alt+insert -> JPA -> LocalContainerEntityManagerFactoryBean
            ctrl+t/f4 : 有办法看结构
    -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--扫描JPA支持的注解-->
        <property name="packagesToScan" value="cn.itsource.aisell.domain" />
        <!--
            告诉Spring我们使用的是哪一个框架来完成JPA规范
            这里就需要我们配置一个适配器
            jpaVendorAdapter:JPA需要配置的适配器(我们会选择hibernate)
        -->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <!--方言-->
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
                <!--
                    建表策略(已经有表有数据,不要删除了)
                -->
                <property name="generateDdl" value="false" />
                <!--是否显示sql-->
                <property name="showSql" value="true" />
            </bean>
        </property>
    </bean>
    <!--4.加上事务-->
    <!--4.1 准备事务管理器-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>
    <!--4.2 开启(注解)事务支持-->
    <tx:annotation-driven transaction-manager="transactionManager" />

</beans>

3.2 集成SpringDataJpa

3.2.1 准备domain(父类)

  1. BaseDomain

jpa中父类domain必需要加上:@MappedSuperclass

/**
 * 泛化:继承关系
 * 在我们JPA,如果要抽取一个父类,就必需加上 @MappedSuperclass
 *  非常明确定的告诉JPA,这是一个用于映射的父类
 */
@MappedSuperclass
public class BaseDomain {
    @Id
    @GeneratedValue
    protected Long id;

   //getter,setter ...
}
  1. Employeee

@Entity
@Table(name = "employee")
public class Employee extends BaseDomain {

    private String username;
    private String password;
    private Integer age;
    private String email;
    //getter,setter ...
   
}

3.2.2 准备Repository接口

/**
 * 关于Employee对象的CRUD(分页排序) 就写完了
 *  泛型一:对哪一个实体做CRUD
 *  泛型二:主键的类型
 */
public interface EmployeeRepository extends JpaRepository<Employee,Long> {
    ...
}

3.2.3 扫描repository

  • repository 就是dao层
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      ...
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      ...
      http://www.springframework.org/schema/data/jpa
      http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
">
   ...

    <!-- 让SpringDataJpa去扫描repository -->
    <jpa:repositories base-package="cn.itsource.aisell.repository"
                      entity-manager-factory-ref="entityManagerFactory"
                      transaction-manager-ref="transactionManager" />

</beans>

四.完成的CRUD功能

4.1 基本的CRUD

  • 查询所有:employeeRepository.findAll()
  • 查询一条数据: employeeRepository.findOne(1L)
  • 添加/修改: employeeRepository.save(employee)
    • 主要看数据库中是否有这个值
    • 修改前先根据id查询,有值就是修改
  • 删除 : employeeRepository.delete(1L)

4.2 分页和排序

4.2.1 排序 Sort

 /**
 * 排序对象
 *  第一个参数:排序的类型(升序还是降序)
 *  第二个参数:排序的属性
 */
Sort sort = new Sort(Sort.Direction.DESC,"age");

List<Employee> list = employeeRepository.findAll(sort);
list.forEach(e-> System.out.println(e));

4.2.2 分页 Pageable接口

注:这里的分页是从0开始的

/**
 * page:第几页(0就是第1页)
 * size:每页条数
 */
Pageable pageable = new PageRequest(0,10);
//分页对象
Page<Employee> list = employeeRepository.findAll(pageable);

list.forEach(e-> System.out.println(e));

4.2.3 分页+排序

Sort sort = new Sort(Sort.Direction.DESC,"age");
/**
 * page:第几页(0就是第1页)
 * size:每页条数
 * sort:排序对象
 */
Pageable pageable = new PageRequest(0,10,sort);
//分页对象
Page<Employee> list = employeeRepository.findAll(pageable);

list.forEach(e-> System.out.println(e));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心之所向...

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值