本篇基于MySQL数据库 8.0.29版本进行说明,需要提前安装MySQL数据库。具体教程详见:《最新版MySQL 8.0 的下载与安装(详细教程)》
一般在新建SpringBoot项目时,勾选了MySQL以及JDBC依赖,可以直接使用,无须再次导入依赖
依赖查找:https://mvnrepository.com/
mysql
mysql-connector-java
8.0.29
org.springframework.boot
spring-boot-starter-jdbc
com.baomidou
mybatis-plus-boot-starter
3.5.1
在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:
数据库中的数据

使用mybatis-plus进行映射
采用了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;
}
@Repository
public interface UserMapper extends BaseMapper {
}
在启动类SbvApplication 增加@MapperScan(“包名”),包名需要一直到mapper包
@SpringBootApplication
@MapperScan("com.wsnk.sbv.mapper")
public class SbvApplication {
public static void main(String[] args) {
SpringApplication.run(SbvApplication.class, args);
}
}
在SbvApplicationTests 测试类中,查询所有用户
@SpringBootTest
class SbvApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void ceshi(){
for (UserPO userPO : userMapper.selectList(null)) {
System.out.println(userPO.toString());
}
}
}
查询成功
