SpringBoot 为我们提供了默认的数据源DataSource。使用默认的数据源很简答,下面我们结合mysql通过一个demo为大家展示如何使用SpringBoot的默认数据源。
1、首先,需要在我们的pom.xml文件中引入 spring-boot-starter-jdbc 依赖 和 mysql-connector-java 数据库驱动依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
SpringBoot-JDBC主要给我们提供了三个功能,第一个就是对数据源的装配,第二个就是提供一个JDBCTemplte
简化我们的使用,第三个就是事务。
2、在application.properties配置文件中定义我们的数据源参数:
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
3、编写一个Dao层使用SpringBoot自动装配的JDBCTemplte来操作我们的数据库。这里我们使用UserDao,编写一个查询用户数据的方法,最终以字符串格式返回。
package com.datasource.datasource_demo.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Component;
/**
* @author #####
* @create 2018-09-09 22:36
**/
@Component
public class UserDao {
@Autowired
JdbcTemplate jdbcTemplate;
public String getAllUserInfo(){
String result = "";
SqlRowSet sqlRowSet = jdbcTemplate.queryForRowSet("Select * from user;");
while (sqlRowSet.next()){
result += "UserName: "+sqlRowSet.getString("user_name") + "\r\n";
}
return result;
}
}
4、接下来编写我们的Service层,UserService:
package com.datasource.datasource_demo.service;
import com.datasource.datasource_demo.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author ######
* @create 2018-09-09 22:37
**/
@Service
public class UserService {
@Autowired
UserDao userDao;
public String getAllUserInfo(){
return userDao.getAllUserInfo();
}
}
5、最后,编写一个Controller接口,UserController:
package com.datasource.datasource_demo.cotroller;
import com.datasource.datasource_demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* @author ######
* @create 2018-09-09 22:37
**/
@RestController
public class UserController {
@Autowired
UserService userService;
@RequestMapping("/userinfo")
@ResponseBody
public String getUserInfo(){
return userService.getAllUserInfo();
}
}
6、启动我们的SpringBoot应用程序,浏览器访问localhost:8080/userinfo,即可得到如下返回结果,与数据库中记录的数据一致:
UserName: linco
数据库记录:
7、SpringBoot-JDBC 也为我们提供了事物的功能。
使用事物,需要使用@EnableTransactionManagement启用对事务的支持(默认打开),然后在需要使用事务的方法上面加上@Transactional即可。
注意,默认只会对运行时异常进行事务回滚,非运行时异常不会回滚事务。如果要使得非运行期异常也回滚,就要使用@Transactional进行相关配置,比如@Transactional(rollbackFor=Exception.class)对所有异常进行回滚不管是运行期还是非运行期异常。