0
点赞
收藏
分享

微信扫一扫

SpringBoot 使用JDBC 连接 Mysql 数据库

juneyale 2022-11-17 阅读 38


一、创建

1、File→New→Project→Spring Initializr

SpringBoot 使用JDBC 连接 Mysql 数据库_mysql

SpringBoot 使用JDBC 连接 Mysql 数据库_mysql_02

二、编写

1、项目结构如下

SpringBoot 使用JDBC 连接 Mysql 数据库_mysql_03

2、创建 User 类

package com.example.mysql.pojo;

import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Table;

@Table("student")
public class User {
@Id
private Integer id;
private String name;
private Integer age;

public Integer getId() {
return id;
}

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

public String getName() {
return name;
}

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

public Integer getAge() {
return age;
}

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

@Override
public String toString() {
return "User{" +
"id=" +id +
", name='" + name + '\'' +
", age='" + age + '\'' +
'}';

}
}

3、创建 UserRepository 接口

package com.example.mysql.dao;

import com.example.mysql.pojo.User;
import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<User, Integer> {
}

4、创建 MysqlController 类

package com.example.mysql.Controller;

import com.example.mysql.dao.UserRepository;
import com.example.mysql.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class MysqlController {
@Autowired
private UserRepository userRepository;

@GetMapping("/users")
public List<User> findAll() {
List<User> result = new ArrayList<>();
userRepository.findAll().forEach((user) -> {
result.add(user);
});

return result;
}
}

5、创建 application.yml

server:
port: 8082
spring:
datasource:
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.2.109:3306/school?useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=utf-8
username: root
password: Abc@123456

三、数据库

创建数据库,连接地址:

SpringBoot 使用JDBC 连接 Mysql 数据库_java_04

四、访问

SpringBoot 使用JDBC 连接 Mysql 数据库_spring_05

 

 

 

 

举报

相关推荐

0 条评论