五、SpringBoot使用JPA完成CRUD

SpringBoot使用JPA完成CRUD

1.什么是JPA

一说JavaWeb,很多小伙伴都知道SSH,这个H代表的就是Hibernate框架,这个小伙伴们都知道,可是什么又是JPA呢?相信许多刚入门的小伙伴听说过但不是特别清楚,首先JPA的全称叫做Java Persistence API,JPA是一个基于O/R映射的标准规范,在这个规范中,JPA只定义标准规则,不提供实现,使用者则需要按照规范中定义的方式来使用。目前JPA的主要实现有Hibernate、EclipseLink、OpenJPA等,事实上,由于Hibernate在数据访问解决技术领域的绝对霸主地位,JPA的标准基本是由Hibernate来主导的。虽然做开发的小伙伴不怎么喜欢度娘,不过度娘关于JPA的介绍个人觉得倒是比较清晰,有兴趣的小伙伴可前去了解下。JPA_百度百科。另外,Spring框架为我们提供了Spring Data JPA这样一个东东,可以减少我们使用JPA时的代码量。
构建项目

2创建SpringBoot项目

创建项目,请参考:初识springboot之快速搭建
如下图1所示:
图片:
我们打开pom.xml可以看到springboot自动为我们添加了spring-data-jpa、mysql-connector-java的支持,如下图5所示:
上图的注释是我添加的,项目默认创建完成后是没有注释的。

<?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>com.example</groupId>
    <artifactId>datajpa</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>DataJPA</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

注意:如果使用内部tomcat运行项目需要将spring-boot-starter-tomcat的scope标签注释掉。

3.配置数据源以及JPA

今后我们修改application.properties文件配置为application.yml配置。.yml配置文件与.properties配置要更清晰更有层次感,可以很明了的看懂配置信息。
我们在resources目录下创建application.yml文件,并且配置DataSource以及JPA,如下所示:
application.yml

 spring:
   datasource:
     url: jdbc:mysql://127.0.0.1:3306/testjpa
     username: root
     password: root
     driver-class-name: com.mysql.jdbc.Driver 
   jpa:
     hibernate:
       ddl-auto: update
       naming:
         physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
     show-sql: true  

4.新建数据库

我平时比较喜欢使用navacat for mysql这个数据库管理工具进行数据库操作,数据库建表代码如下:

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `t_id` int(11) NOT NULL,
  `t_name` varchar(255) DEFAULT NULL,
  `t_age` int(11) DEFAULT NULL,
  `t_address` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`t_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

建成数据库和表后如图所示:
图片

5.代码编写

5.1创建实体

根据数据库中的字段对应建立一个实体类UserEntity,实体类中代码如下:

package com.crazyang.domain;

import javax.persistence.*;
import java.io.Serializable;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author crazyang
 * @Desciption:
 * @Date 2018-6-6 17:23
 */
@Entity
@Table(name="t_user")
public class UserEntity implements Serializable {
    @Id
    @GeneratedValue
    @Column(name="t_id")
    private Long id;
    @Column(name="t_name")
    private String name;
    @Column(name="t_age")
    private int age;
    @Column(name="t_address")
    private String address;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Long getId() {

        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}

5.2创建JPA

既然实体类我们也已经创建完成了,那么接下来我们需要使用SpringDataJPA来完成数据库操作,我们新建名字叫做jpa的package,然后创建UserJPA接口并且继承SpringDataJPA内的接口作为父类,代码如下:

package com.crazyang.jpa;

import com.crazyang.domain.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

import java.io.Serializable;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author crazyang
 * @Desciption:
 * @Date 2018-6-6 17:32
 */
public interface UserJPA extends JpaRepository<UserEntity, Long>, JpaSpecificationExecutor<UserEntity>, Serializable {

}

我们UserJPA继承了JpaRepository接口(SpringDataJPA提供的简单数据操作接口)、JpaSpecificationExecutor(SpringDataJPA提供的复杂查询接口)、Serializable(序列化接口)。
我们并不需要做其他的任何操作了,因为SpringBoot以及SpringDataJPA会为我们全部搞定,SpringDataJPA内部使用了类代理的方式让继承了它接口的子接口都以spring管理的Bean的形式存在,也就是说我们可以直接使用@Autowired注解在spring管理bean使用

5.3编写CRUD方法

新建UserController类,用于请求转发,代码如下:

package com.crazyang.controller;

import com.crazyang.domain.UserEntity;
import com.crazyang.jpa.UserJPA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author crazyang
 * @Desciption:
 * @Date 2018-6-6 17:21
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserJPA userJPA;

    /**
     * 查询所有数据
     *
     * @return
     */
    @RequestMapping("/list")
    public List<UserEntity> list() {
        return  userJPA.findAll();
    }

    @RequestMapping("/save")
    public UserEntity save(UserEntity entity) {
        return    userJPA.save(entity);
    }

    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public List<UserEntity> delete(Long id) {
        userJPA.deleteById(id);
        return userJPA.findAll();
    }


}

6.启动项目

启动项幕后,由于数据库中并无数据,直接访问127.0.0.1:8080/user/list显示为空,首先向数据库中插入数据,在浏览器中输入127.0.0.1:8080/user/save?name=admin&age=16&address=shanghai
效果如下图:
这里写图片描述
重复插入后,再次访问127.0.0.1:8080/user/list,效果如下图所示:
这里写图片描述

7.总结

本章介绍了如何使用Spring Boot JPA进行数据交互,可以看到,使用JPA可以大量减少Dao代码,提升开发效率。

猜你喜欢

转载自blog.csdn.net/java_mdzy/article/details/80613406