SpringBoot 项目连接MySQL 数据库
·
导入依赖
一般在新建SpringBoot 项目时,勾选了的依赖无需再次导入,可以直接使用。依赖查找:【直达:https://mvnrepository.com/】。
导入MySQL 版本依赖。
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
导入mybatis-plus 依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>3.5.11</version>
</dependency>
连接数据库
在【application.yml文件】中进行连接数据库的简单配置,【yml文件】中格式不能错位,不然不会读取配置。
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:mysql://localhost:3306/yourDatabase?useUnicode=true&characterEncoding=utf-8&useSSL=true
username: root
password:
测试
创建实体类,采用Lombok 简化代码.
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("sector")
public class SectorPO {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@TableField("code")
private String code;
@TableField("name")
private String name;
@TableField("`desc`")
private String desc;
}
在Mapper 包下创建【SectorMapper 文件】
@Mapper
public interface SectorMapper extends BaseMapper<SectorPO> {
}
在启动类StockApplication 增加@MapperScan(“包名”)注解,包名需要一直到mapper 包
@SpringBootApplication
@MapperScan("com.wsnk.stock.mapper")
public class StockApplication {
public static void main(String[] args) {
SpringApplication.run(StockApplication.class, args);
}
}
测试
在StockApplicationTests 测试类中,查询表中数据。
@SpringBootTest
class StockApplicationTests {
@Autowired
private SectorMapper sectorMapper;
@Test
public void ceshi(){
for (SectorPO sectorPO : sectorMapper.selectList(null)) {
System.out.println(sectorPO);
}
}
}
成功查询。
更多推荐
所有评论(0)