SpringBoot15:整合JPA

文章与CSDN同步,欢迎访问:https://blog.csdn.net/qq_40280582/article/details/107549707
代码地址:https://gitee.com/ilovemo/spring-data-jpa-study

简单的REST CRUD示例

依赖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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.godfrey</groupId>
    <artifactId>springbootjpa</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-data-jpa</name>
    <description>Spring-Data-JPA project for Spring Boot</description>

    <properties>
        <java.version>11</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>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
    </dependencies>

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

</project>

相关配置

server:
  port: 8080
  servlet:
    context-path: /
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost/jpa?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&useServerPrepStmts=false&rewriteBatchedStatements=true&useSSL=false
    username: root
    password: root
  jpa:
    database: mysql
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    show-sql: true
    hibernate:
      ddl-auto: update

ddl-auto

  • create:每次运行程序时,都会重新创建表,故而数据会丢失
  • create-drop:每次运行程序时会先创建表结构,然后待程序结束时清空表
  • upadte:每次运行程序,没有表时会创建表,如果对象发生改变会更新表结构,原有数据不会清空,只会更新(推荐使用)
  • validate:运行程序会校验数据与数据库的字段类型是否相同,字段不同会报错
  • none: 禁用DDL处理

实体类

package com.godfrey.pojo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;

/**
 * 实体类
 *
 * @author godfrey
 * @date 2020-07-23
 */
@Entity
@ApiModel("用户实体")
@Table(name = "tb_user")
@Data
public class User implements Serializable {

    private static final long serialVersionUID = 4874167929879128188L;

    @Id
    @ApiModelProperty("主键id")
    private Integer id;

    @ApiModelProperty("用户名")
    @Column(name = "username", unique = true, nullable = false, length = 64)
    private String username;

    @ApiModelProperty("密码")
    @Column(name = "password", nullable = false, length = 64)
    private String password;

    @ApiModelProperty("邮箱")
    @Column(name = "email", length = 64)
    private String email;
}

持久层

package com.godfrey.repository;

import com.godfrey.pojo.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

/**
 * Dao层
 *
 * @author godfrey
 * @date 2020-07-23
 */
@Repository
public interface UserRepository extends JpaRepository<User,Integer> {
}

服务接口层

package com.godfrey.service;

import com.godfrey.pojo.User;
import org.springframework.data.domain.Page;

/**
 * 服务接口层
 *
 * @author godfrey
 * @date 2020-07-23
 */
public interface UserService {

    /**
     * 保存对象
     *
     * @param user 1
     * @return com.godfrey.pojo.User
     */
    User save(User user);

    /**
     * 通过id删除User
     *
     * @param userId 1
     */
    void deleteById(Integer userId);

    /**
     * 通过id修改User信息
     *
     * @param userId 1
     * @param user   2
     * @return com.godfrey.pojo.User
     */
    User updateUser(Integer userId, User user);

    /**
     * 查询用户信息
     *
     * @param userId 1
     * @return com.godfrey.pojo.User
     */
    User getUserInfo(Integer userId);

    /**
     * 分页查询用户
     *
     * @param pageNum  1
     * @param pageSize 2
     * @return org.springframework.data.domain.Page<com.godfrey.pojo.User>
     */
    Page<User> pageQuery(Integer pageNum, Integer pageSize);

}

服务实现层

package com.godfrey.service.impl;

import com.godfrey.pojo.User;
import com.godfrey.repository.UserRepository;
import com.godfrey.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 服务实现层
 *
 * @author godfrey
 * @date 2020-07-23
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public User save(User user) {
        return userRepository.save(user);
    }

    @Override
    public void deleteById(Integer userId) {
        userRepository.deleteById(userId);
    }

    @Override
    public User updateUser(Integer userId, User user) {
        user.setId(userId);
        return userRepository.saveAndFlush(user);
    }

    @Override
    public User getUserInfo(Integer userId) {
        Optional<User> optional = userRepository.findById(userId);
        return optional.orElseGet(User::new);
    }

    @Override
    public Page<User> pageQuery(Integer pageNum, Integer pageSize) {
        return userRepository.findAll(PageRequest.of(pageNum - 1, pageSize));
    }
}

控制层

package com.godfrey.controller;

import com.godfrey.pojo.User;
import com.godfrey.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

/**
 * 控制层
 *
 * @author godfrey
 * @date 2020-07-23
 */
@Api(tags = {"用户管理"})
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "保存对象")
    @PostMapping()
    public User saveUser(@ApiParam(value = "用户") @RequestBody User user) {
        return userService.save(user);
    }

    @ApiOperation(value = "通过id删除User")
    @DeleteMapping("/{id}")
    public void deleteUser(@ApiParam(value = "用户id") @PathVariable("id") Integer userId) {
        userService.deleteById(userId);
    }

    @ApiOperation(value = "通过id删除User")
    @PutMapping("/{id}")
    public User updateUser(@ApiParam(value = "用户id") @PathVariable("id") Integer userId, @ApiParam(value = "用户") User user) {
        return userService.updateUser(userId, user);
    }

    @ApiOperation(value = "查询用户信息")
    @GetMapping("{id}")
    public User getUserInfo(@ApiParam(value = "用户id") @PathVariable("id") Integer userId) {
        return userService.getUserInfo(userId);
    }

    @ApiOperation(value = "分页查询用户")
    @GetMapping("/list")
    public Page<User> pageQuery(
            @ApiParam(value = "启始页") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @ApiParam(value = "每页大小") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        return userService.pageQuery(pageNum, pageSize);
    }
}

Swagger2配置

package com.godfrey.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;

/**
 * Swagger2配置
 *
 * @author godfrey
 * @date 2020-07-23
 */
@Configuration //配置类
@EnableSwagger2 // 开启Swagger2的自动配置
public class Swagger2Config {

    //配置docket以配置Swagger具体参数
    @Bean
    public Docket docket() {

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("对弈")
                .select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口
                .apis(RequestHandlerSelectors.basePackage("com.godfrey.controller"))
                .build();
    }

    //配置文档信息
    private ApiInfo apiInfo() {
        Contact contact = new Contact("godfrey", "https://www.duiyi.xyz", "2424496907@qq.com");

        return new ApiInfo(
                "JPA Study", // 标题
                "Spring Data JPA 学习", // 描述
                "v1.0", // 版本
                "https://gitee.com/ilovemo", // 组织链接
                contact, // 联系人信息
                "Apache 2.0", // 许可
                "http://www.apache.org/licenses/LICENSE-2.0", // 许可连接
                new ArrayList<>()// 扩展
        );

    }

}

效果

posted @ 2020-07-23 22:33  对弈  阅读(25)  评论(0编辑  收藏