当前位置:   article > 正文

SpringBoot项目连接MySQL数据库_mysql pom

mysql pom

前言

本篇基于MySQL数据库 8.0.29版本进行说明,需要提前安装MySQL数据库。具体教程详见:《最新版MySQL 8.0 的下载与安装(详细教程)》

一、导入依赖

一般在新建SpringBoot项目时,勾选了MySQL以及JDBC依赖,可以直接使用,无须再次导入依赖
依赖查找:https://mvnrepository.com/

1.在pom文件中导入MySQL依赖

<dependency>
	<groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.29</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

2.在pom文件中导入JDBC依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
  • 1
  • 2
  • 3
  • 4

3.在pom文件中导入mybatis-plus依赖

<dependency>
	<groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

二、连接数据库

在application.yml中进行连接数据库的简单配置,yml文件中格式不能错位,不然不会读取配置

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.zaxxer.hikari.HikariDataSource
    url: jdbc:mysql://localhost:3306/sbvue?useUnicode=true&characterEncoding=utf-8&useSSL=true
    username: root
    password: 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

数据库中的数据
在这里插入图片描述

三、测试

使用mybatis-plus进行映射

1.创建UserPo实体类

采用了Lombok简化代码

@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("user")
public class UserPO {
    @TableId(value = "id",type = IdType.AUTO)
    private int id;
    @TableField("name")
    private String name;
    @TableField("age")
    private int age;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

2.在Mapper包下创建UserMapper

@Repository
public interface UserMapper extends BaseMapper<UserPO> {
}
  • 1
  • 2
  • 3

3.在启动类增加注解

在启动类SbvApplication 增加@MapperScan(“包名”),包名需要一直到mapper包

@SpringBootApplication
@MapperScan("com.wsnk.sbv.mapper")
public class SbvApplication {
    public static void main(String[] args) {
        SpringApplication.run(SbvApplication.class, args);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

4.测试

在SbvApplicationTests 测试类中,查询所有用户

@SpringBootTest
class SbvApplicationTests {
    @Autowired
    private UserMapper userMapper;
    @Test
    public void ceshi(){
        for (UserPO userPO : userMapper.selectList(null)) {
            System.out.println(userPO.toString());
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

查询成功
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/289947
推荐阅读
相关标签
  

闽ICP备14008679号