基于spring boot+spring data jpa实现单表CRUD

面试中经常会有几轮,机试必不可少,下面就给大家分享一下,基于spring boot+spring data jpa 实现单表的增删改查
开发环境及开发工具:IDEA+SQLyogEnt+jdk1.8+mysql5.5

  • 1环境的搭建和数据库建表
1.在数据库中创建库:jpa
2.创建表:cst_customer
DDL信息:
	
create table:
CREATE TABLE `cst_customer` (
   `cust_id` bigint(20) NOT NULL AUTO_INCREMENT,
   `cust_address` varchar(255) DEFAULT NULL,
   `cust_industry` varchar(255) DEFAULT NULL,
   `cust_level` varchar(255) DEFAULT NULL,
   `cust_name` varchar(255) DEFAULT NULL,
   `cust_phone` varchar(255) DEFAULT NULL,
   `cust_source` varchar(255) DEFAULT NULL,
   PRIMARY KEY (`cust_id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
 测试数据可以自己手动补上,建表成功后,F5刷新一下数据库,即可看到自己创建的表
  • maven仓库的配置
    maven的本地安装包路基,maven的setting.xml路基配置(里面配置的私服路基),本体仓库的路基的配置
    IDEA工具里面配置:setting–>maven在这里插入图片描述
  • 我的maven工程架构(先创建一个maven工程,不必详说)
    在这里插入图片描述
  • 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>org.lijialin</groupId>
    <artifactId>jpa-day03-spec</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <spring.version>5.0.2.RELEASE</spring.version>
        <hibernate.version>5.0.1.Final</hibernate.version>
    </properties>
    <dependencies>
        <!-- junit单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</version>
        </dependency>
        <!-- spring beg -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- spring对orm框架的支持包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- spring end -->

        <!-- hibernate对jpa的支持包 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.2.1.Final</version>
        </dependency>
        <!-- c3p0 -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <!-- log日志 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.6</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.6</version>
        </dependency>


        <!-- Mysql and MariaDB -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <!-- spring data jpa 的坐标-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.9.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- el beg 使用spring data jpa 必须引入 -->
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>2.2.4</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.el</artifactId>
            <version>2.2.4</version>
        </dependency>
        <!-- el end -->

    </dependencies>

</project>
  • resource包项目创建配置项目的配置文件:applicationContext.xml
<?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 和 spring data jpa的配置-->

    <!-- 1.创建entityManagerFactory对象交给spring容器管理-->
    <bean id="entityManagerFactoty" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--配置的扫描的包(实体类所在的包) -->
        <property name="packagesToScan" value="org.lijialin.domain" />
        <!-- jpa的实现厂家 -->
        <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>

    <!--2.创建数据库连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="root"></property><!--连接我本地数据库的用户名:root-->
        <property name="password" value="root"></property><!--连接我本地数据库的密码:root-->
        <property name="jdbcUrl" value="jdbc:mysql:///jpa" ></property><!--连接我在数据库创建的库:jpa;'/'相当于:localhost:127.0.01-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    </bean>

    <!--3.整合spring dataJpa--> <!--对此包下的dao接口进行动态代理增强-->
    <jpa:repositories base-package="org.lijialin.dao" transaction-manager-ref="transactionManager"
                   entity-manager-factory-ref="entityManagerFactoty" ></jpa:repositories>

    <!--4.配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactoty"></property>
    </bean>

    <!-- 4.txAdvice-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!-- 5.aop 此处面向切面的配置用不到,但配置了也不影响-->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* org.lijialin.service.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
    </aop:config>


    <!--5.声明式事务,项目中没用到也可不配 -->
	<aop:config>
        <aop:pointcut id="pointcut" expression="execution(* org.lijialin.service.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
    </aop:config>
    <!-- 6. 配置包扫描-->
    <context:component-scan base-package="org.lijialin" ></context:component-scan>
</beans>
  • 创建数据访问层dao接口:CustomerDao
package org.lijialin.dao;

import org.lijialin.domain.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

/**
 * @Author *佳林
 * @Date 2019/8/17
 * 符合SpringDataJpa的dao层接口规范
 *      JpaRepository<操作的实体类类型,实体类中主键属性的类型>
 *          * 封装了基本CRUD操作
 *      JpaSpecificationExecutor<操作的实体类类型>
 *          * 封装了复杂查询(分页)
 *          程序执行时,动态生成实现类对象
 */
public interface CustomerDao extends JpaRepository<Customer,Long>,JpaSpecificationExecutor<Customer> {
}

  • 创建数据持久层实体类:Customer
package org.lijialin.domain;

import javax.persistence.*;

/**
 * @Author *佳林
 * @Date 2019/8/16
 * 1.实体类和表的映射关系
 *      @Eitity
 *      @Table
 *  2.类中属性和表中字段的映射概念性
 *      @Id
 *      @GeneratedValue
 *      @Column
 */
@Entity
@Table(name = "cst_customer")
public class Customer {
    /**
     * @Id:声明主键的配置
     * @GeneratedValue:配置主键的生成策略
     *      strategy
     *          GenerationType.IDENTITY :自增,mysql
     *                 * 底层数据库必须支持自动增长(底层数据库支持的自动增长方式,对id自增)比如MySQL数据库
     *          GenerationType.SEQUENCE : 序列,oracle
     *                  * 底层数据库(如Oracle数据库)必须支持序列方可使用SEQUENCE
     *          GenerationType.TABLE : jpa提供的一种机制,通过一张数据库表的形式帮助我们完成主键自增
     *          GenerationType.AUTO : 由程序自动的帮助我们选择主键生成策略
     * @Column:配置属性和字段的映射关系
     *      name:数据库表中字段的名称
     */
    //客户主键
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "cust_id")
    private Long custId;
    //客户名称
    @Column(name = "cust_name")
    private String custName;
    //客户来源
    @Column(name="cust_source")
    private String custSource;
    //客户级别
    @Column(name="cust_level")
    private String custLevel;
    //客户的联系方式
    @Column(name="cust_industry")
    private String custIndustry;
    //客户的联系方式

    @Column(name="cust_phone")
    private String custPhone;
    //客户地址
    @Column(name="cust_address")
    private String custAddress;

    public Long getCustId() {
        return custId;
    }

    public void setCustId(Long custId) {
        this.custId = custId;
    }

    public String getCustName() {
        return custName;
    }

    public void setCustName(String custName) {
        this.custName = custName;
    }

    public String getCustSource() {
        return custSource;
    }

    public void setCustSource(String custSource) {
        this.custSource = custSource;
    }

    public String getCustLevel() {
        return custLevel;
    }

    public void setCustLevel(String custLevel) {
        this.custLevel = custLevel;
    }

    public String getCustIndustry() {
        return custIndustry;
    }

    public void setCustIndustry(String custIndustry) {
        this.custIndustry = custIndustry;
    }

    public String getCustPhone() {
        return custPhone;
    }

    public void setCustPhone(String custPhone) {
        this.custPhone = custPhone;
    }

    public String getCustAddress() {
        return custAddress;
    }

    public void setCustAddress(String custAddress) {
        this.custAddress = custAddress;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "custId=" + custId +
                ", custName='" + custName + '\'' +
                ", custSource='" + custSource + '\'' +
                ", custLevel='" + custLevel + '\'' +
                ", custIndustry='" + custIndustry + '\'' +
                ", custPhone='" + custPhone + '\'' +
                ", custAddress='" + custAddress + '\'' +
                '}';
    }
}


  • 创建测试类:SpecTest
package org.lijialin.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.lijialin.dao.CustomerDao;
import org.lijialin.domain.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.persistence.criteria.*;
import java.util.List;

/**动态查询
 * 测试类
 * @Author 李佳林
 * @Date 2019/8/17
 */
//声明spring提供的单元测试环境
@RunWith(SpringJUnit4ClassRunner.class)
//指定spring容器的配置信息
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpecTest {
    @Autowired
    private CustomerDao customerDao;

    /**
     * 根据条件查询单个对象
     */
    @Test
    public void testSpec1(){
        //匿名内部类
        /**
         * 自定义查询条件
         *      1.实现Specification接口(提供泛型,查询对象类型)
         *      2.实现toPredicate方法(构造查询条件)
         *      3.需要借助方法参数中的两个参数
         *          root:获取需要查询的对象的属性
         *          CriteriaBuilder:构造查询条件,内部封住了很多的查询条件(模糊匹配,精准匹配)
         *      案例:
         *          根据客户名称查询
         *          查询条件:
         *              1.查询方式
         *              2.比较的属性名称
         *                  存于root对象中
         */
        Specification<Customer> spec = new Specification<Customer>() {
            @Override
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<Object> custName = root.get("custName");
                /**
                 * 第一个参数:需要比较的属性(path对象)
                 * 第二个参数:当前需要比较的值
                 */
                //进行精准匹配(比较属性,比较的属性的取值)
                //Predicate predicate = cb.equal(custName, "尚学堂");
                return cb.equal(custName, "尚学堂");
            }
        };
        Customer customer = customerDao.findOne(spec);
        System.out.println(customer);
    }

    /**动态查询中
     * 多个条件的查询
     */
    @Test
    public void testSpec2(){
        /**
         * root:获取属性
         *      客户名
         *      属性行业
         *  cb:构造查询
         *      1.构造客户名的精准匹配查询
         *      2.构造所属行业的精准匹配查询
         *      3.将以上2个查询联系起来
         */
        Specification<Customer> spec = new Specification<Customer>() {
            @Override
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //客户名
                Path<Object> custName = root.get("custName");
                //所属行业
                Path<Object> custIndustry = root.get("custIndustry");

                /**
                 * 构造查询
                 * 1.构造客户名的精准匹配查询
                 */
                //第一个参数:path(属性),第二个参数:属性的取值
                Predicate p1 = cb.equal(custName, "黑马程序员");
                //2.将所属行业的精准匹配查询
                Predicate p2 = cb.equal(custIndustry, "IT教育");
                //3.将多个查询条件组合到一起,组合(满足条件1并且满足条件2:与关系,满足条件1或满足条件2:或关系)
                //ch.or();以或的形式拼接多个查询条件
                Predicate and = cb.and(p1, p2);

                return and;
            }
        };
        Customer customer = customerDao.findOne(spec);
        System.out.println(customer);
    }

    /**
     * 案例:完成根据客户名称的模糊匹配,返回客户列表
     *
     * equal 方法: 可以直接得到path对象(属性),然后进行比较即可
     * 而以下方法:
     *      gt,lt,ge,le,like : 先得到path对象,根据path指定比较的参数类型,再去进行比较
     *          指定参数类型:path.as(类型的字节码对象)
     */
    @Test
    public void testSpec3(){
        //构造查询条件
        Specification<Customer> spec = new Specification<Customer>() {
            @Override
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //查询属性:客户名
                Path<Object> custIndustry = root.get("custIndustry");
                //查询方式:模糊匹配(指定以客户名称进行模糊匹配,并且客户名称是字符串类型)
                Predicate like = cb.like(custIndustry.as(String.class), "IT%");

                return like;
            }
        };
       /* List<Customer> list = customerDao.findAll(spec);
        for (Customer customer : list) {
            System.out.println(customer);
        }*/
        /**
         * 添加排序
         *  创建排序对象,需要调用构造方法实训sort对象
         *  第一个参数:排序的顺序(倒序,正序)
         *      sort.Direction.DESC : 倒序
         *      sort.Direction.ASC : 升序
         *  第二个参数:排序的属性名称
         */
        //按custId倒序排序
        Sort sort = new Sort(Sort.Direction.DESC,"custId");
        List<Customer> customerList = customerDao.findAll(spec, sort);
        for (Customer customer : customerList) {
            System.out.println(customer);
        }
    }

    /**
     * 分页查询
     *      Specification: 查询条件
     *      Pageable : 分页参数
     *      分页参数:查询的页码,每页查询的条数
     *      findAll(Specification,Pageable) : 带有条件的分页
     *      findAll(Pageable) : 每页条件的分页
     *   返回:Page(springDataJpa 为我们封装好的pageBean对象,数据列表,总共条数)
     */
    @Test
    public void testSpec4(){
        Specification spec = null;
        /**
         * PageRequest对象是Pageable接口的实现类
         *  创建PageRequest的过程中:需要调用其构造方法并传入两个参数
         *      第一个参数: 当前查询的页数(从0开始)
         *      第二个参数: 每页查询的数量
         */
        PageRequest pageRequest = new PageRequest(0, 2);
        //分页查询
        Page<Customer> page = customerDao.findAll(null, pageRequest);
        //得到数据集合
        System.out.println(page.getContent());
        //得到总条数
        System.out.println(page.getTotalElements());
        //得到总页数
        System.out.println(page.getTotalPages());
    }
}

切记:测试类的包结构和接口类的包结构一致.
因为spring data jpa框架可以为我们动态的创建接口的实现类,可以不用在server层做接口的实现.
OK,基于spring boot 和spring data jpa框架快速实现单表的CRUD功能做好了.
有什么不足的地方,欢迎在下方留言

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值