SpringBoot教程(二)|SpringBoot项目配置数据库
jdbc,SpringBoot
·
1.导入依赖
搭建是Springboot可以看我上一篇 使用maven搭建Springboot
在pom.xml中添加mysql连接需要的依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
添加lombok依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
二、添加数据库配置
在application.yml中进行连接数据库的简单配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true
username: root
password: root
数据库添加用户表
三、测试
使用mybatis-plus进行映射
1.创建UserDomian 实体类
采用了Lombok简化代码
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("user")
public class UserDomian {
@TableId(value = "id",type = IdType.AUTO)
private int id;
@TableField("name")
private String name;
@TableField("address")
private String address;
}
2.在Mapper包下创建UserMapper类
@Repository
public interface UserMapper extends BaseMapper<UserDomian> {
}
3.TestController 添加接口
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
UserMapper userMapper;
@GetMapping("/hello")
public String hello() {
return "Hello World";
}
@GetMapping("/getUsers")
public String getUsers() {
return userMapper.selectList(null).toString();
}
}
4.在启动类增加注解
在启动类SbvApplication 增加@MapperScan(“包名”),包名需要指定到mapper包
@SpringBootApplication
@MapperScan("com.mansai.mapper")
public class SpringStartApplication {
public static void main(String[] args) {
SpringApplication.run(SpringStartApplication.class,args);
}
}
启动程序,访问接口 localhost:8081/test/getUsers。
更多推荐
所有评论(0)