SpringBoot集成jdbc
1.简述
Springboot对于数据访问层,不管是SQL还是NOSQL,SpringBoot底层都是采用SpringData的方式统一处理。SpringData是Spring家族中与SpringBoot、SpringCloud 齐名且知名项目。
2.集成jdbc说明
(1)添加依赖
在pom.xml文件中加入依赖,内容如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!--JDBC依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--mysql依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
(2)application.[yml、properties]文件中配置数据库连接
application.[yml、properties]文件中配置数据库连接,内容如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
spring: datasource: url: jdbc:mysql://localhost:3306/test_jdbc?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=UTC username: root password: 123 driver-class-name: com.mysql.cj.jdbc.Driver
(3)jdbc实现
在test_jdbc数据库中创建tbl_user表并插入数据,语句如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
create table tbl_user( id int not null auto_increment, accountName varchar(50) not null comment '账号', password varchar(50) not null comment '密码', primary key(id))ENGINE=INNODB DEFAULT CHARSET=utf8; insert into tb_user(accountName,password)values('admin','123456'); insert into tb_user(accountName,password)values('ceshi','123456');
创建UserBean实体类,代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class UserBean { private int id; private String accountName; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
新建UserDao实现dao层,代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@Repository public class UserDao { @Autowired JdbcTemplate jdbcTemplate; public List<Map<String, Object>> selectUser() { List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from tbl_user"); if (list.size() > 0) { return list; } return null; } }
为了简单,直接新建UserController,代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@Controller @RequestMapping("/user") public class UserController { @Autowired UserDao userDao; @RequestMapping(method= RequestMethod.GET,produces="text/html;charset=UTF-8") public String hello(HttpServletRequest req, HttpServletResponse resp) throws IOException { List<Map<String, Object>> list = userDao.selectUser(); resp.getWriter().write(list.toString()); resp.getWriter().close(); return null; } }
(4)测试
启动项目,浏览器输入localhost:8080/user,得到数据,整合成功。