1. 程式人生 > 實用技巧 >SpringBoot15:整合JPA

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", "[email protected]");

        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<>()// 擴充套件
        );

    }

}