springboot项目开发过程参考(Spring Data JPA + Spring Data REST)

springboot项目开发过程参考(Spring Data JPA + Spring Data REST)

依赖环境

  • java

    jdk版本 1.8

  • maven

    1
    2
    mvn -v
    3.6.3

开发工具

  • IDEA
  • postman 测试后端接口
  • vscode

新建项目

  • 项目结构

    DemoApplication: 项目启动类
    application.properties: 配置文件
    pom.xml: 运行环境,maven仓库

框架:Spring Data JPA + Spring Data REST

  • Spring Data JPA,使开发者使用极简的代码实现对数据库的访问和操作。它提供了包括增删改查等在内的基本功能,且易于扩展。
  • Spring Data REST,基于Spring Data的repository之上,可以把 repository 自动输出为REST资源,支持Spring Data JPA

1.导入maven依赖

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?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.4.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<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>
<!--Spring Data REST-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
<version>3.3.0.RELEASE</version>
</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>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.4.0</version>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
</plugins>
</build>

</project>

2.properties文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#restful
spring.data.rest.base-path=/db
server.port=18888

#达梦
#spring.datasource.url=jdbc:dm://localhost:5236?schema=DEMOSTORE
#spring.datasource.username=SYSDBA
#spring.datasource.password=12345qwert
#spring.datasource.driver-class-name=dm.jdbc.driver.DmDriver
#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.DmDialect
#spring.jpa.hibernate.ddl-auto=update
#spring.jpa.show-sql=true

#mysql
#com.mysql.cj.jdbc.Driver
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/demojava?characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
spring.datasource.username=root
spring.datasource.password=123qwe

#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.DmDialect
spring.jpa.hibernate.ddl-auto=update
#spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true

3.entity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.example.demo.entity;

import lombok.Data;
import javax.persistence.*;

@Entity //jpa实体类标识
@Data //LomBok插件,省略get set
//@Table(name = "SysUser") // 指定数据库的表名
public class SysUser {

@Id //主键
private Integer userId;

private String userName;

private String userType;

private String password;

}

4.repository

1
2
3
4
5
6
7
8
9
10
11
package com.example.demo.repository;

import com.example.demo.entity.SysUser;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
// 相当于UserDao
// 将UserRepository继承JpaRepository就可以有对应的增删改查方法
public interface UserRepository extends JpaRepository<SysUser,Integer>{
}

不需要通过controller,即可使用postman查看接口

5.添加查询方法

  • 使用

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    import com.example.demo.entity.SysUser;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.jpa.repository.Query;
    import org.springframework.stereotype.Repository;

    import java.util.List;

    @Repository
    // 相当于UserDao
    // 将UserRepository继承JpaRepository就可以有对应的增删改查方法
    public interface UserRepository extends JpaRepository<SysUser,Integer>{

    public SysUser findByUserIdAndPassword(Integer userId, String password);

    @Query(value = "select * from sys_user u where u.user_id=?1 and u.password=?2", nativeQuery = true)
    public List<SysUser> findByOwnMethod(Integer userId, String password);

    }
  • jpa自动生成sql

    spring-data-jpa会根据方法的名字来自动生成sql语句,只需要按照方法定义的规则即可。

    1
    public SysUser findByUserIdAndPassword(Integer userId, String password);

    上面的方法findByUserIdAndPassword,以findBy开头,sql的where部分就是UserIdAndPassword,被spring-data-jpa翻译之后就编程了下面这种形态:

    1
    select * from user where userId = ? and password = ?
  • 自定义sql

    使用@Query注解,写原生sql

    1
    2
    @Query(value = "select * from sys_user u where u.user_id=?1 and u.password=?2", nativeQuery = true)
    public List<SysUser> findByOwnMethod(Integer userId, String password);

6.service

主要有两个作用

  • 1 单独的服务

  • 2 包装repository供controller使用

    1
    2
    3
    4
    public interface UserService {

    public SysUser findUserOrNot(Integer userId, String password);
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    @Service
    public class UserServiceImpl implements UserService{
    private final UserRepository userRepository;

    @Autowired
    UserServiceImpl(UserRepository userRepository) {
    this.userRepository = userRepository;
    }

    @Override
    public SysUser findUserOrNot(Integer userId, String password) {
    return userRepository.findByUserIdAndPassword(userId, password);
    }
    }

7.controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.example.demo.controller;

import com.example.demo.entity.SysUser;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/define")
public class UserController {

@Autowired
UserRepository userRepository;

@Autowired
UserService userService;

@RequestMapping("/login")
public ResponseEntity<Map> login(Integer userId, String password) {
Map map = new HashMap<>();
SysUser sysUser = userRepository.findByUserIdAndPassword(userId, password);
map.put("code", "200");
map.put("message", "success");
map.put("user", sysUser);
return new ResponseEntity<Map>(map, HttpStatus.OK);
}

@RequestMapping("/login2")
public ResponseEntity<Map> login2(Integer userId, String password) {
Map map = new HashMap<>();
SysUser sysUser = userService.findUserOrNot(userId, password);
map.put("code", "200");
map.put("message", "success");
map.put("user", sysUser);
return new ResponseEntity<Map>(map, HttpStatus.OK);
}

}

  • 1 直接访问repository
    1
    http://localhost:18888/define/login?userId=1&password=123
  • 2 访问service
    1
    http://localhost:18888/define/login2?userId=1&password=123

8.学习链接

Spring Data Jpa的使用:https://www.jianshu.com/p/c23c82a8fcfc