(三)spring-boot利用JPA操作mysql数据库

引入依赖

1
2
3
4
5
6
7
8
9
10
11
12
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

添加配置

1
2
3
4
5
6
7
8
9
10
11
spring:
datasource:
url: "jdbc:mysql://127.0.0.1:3306/test"
username: root
password: "123456"
#driver-class-name: com.mysql.jdbc.Driver
driver-class-name: com.mysql.cj.jdbc.Driver
max-idle: 10
max-wait: 10000
min-idle: 5
initial-size: 5

创建相关文件

Pojo文件

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

import lombok.*;

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

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Table(name="test")
@Entity
public class Test implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "name")
private String name;
}

Repository文件

1
2
3
4
5
6
7
8
9
package com.example.dao.repository;

import com.example.dao.pojo.Method;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface TestRepository extends JpaRepository<Method, Integer> {
}

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
package com.example;

import com.example.dao.repository.MethodRepository;
import com.example.middleware.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/api/mysql")
public class DebugMysql {
private final TestRepository testRepository;

@Autowired
public DebugMysql(TestRepository testRepository) {
this.testRepository = testRepository;
}
@RequestMapping("/test/all")
public Object search() {
Map<String, Object> result = new HashMap<>();
result.put("list", this.testRepository.findAll());
return result;
}
}

启动服务, 访问 http://localhost:18081/api/mysql/test/all

说明

  • 上述代码仅用于演示,实际项目中应基于代码分层组织代码
  • TestRepository仅声明接口就可以使用,**本人半吊子水准,原理待研究**

常见问题

  • Registered driver with driverClassName=com.mysql.jdbc.Driver was not found

原因为: com.mysql.jdbc.Driver 已经被替换为 com.mysql.cj.jdbc.Driver , 修改配置文件中的 driver-class-name: com.mysql.cj.jdbc.Driver

  • Warning : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning

在配置文件中增加:

1
2
3
spring:
jpa:
open-in-view: false

(三)spring-boot利用JPA操作mysql数据库
http://go.zhangdeman.cn/archives/1adb41f8.html
作者
白茶清欢
发布于
2022年1月19日
许可协议