本节是对springboot-jdbc操作数据库简要介绍及配置数据库操作方法,这里不在介绍mysql数据库安装及操作。如需要安装软件及工具,请加qq或者微信1057718341联系。
mysql安装:https://jingyan.baidu.com/article/f3ad7d0ffc061a09c3345bf0.html
mysql客户端:https://www.navicat.com.cn/products
创建项目
File->New->Project->New Module
选择web、mysql、jdbc等jar包,点击下一步。
创建完成后如下:
启动项目错误
2018-05-05 13:38:10.419 INFO 7568 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
2018-05-05 13:38:10.435 INFO 7568 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-05-05 13:38:10.560 INFO 7568 --- [ main] utoConfigurationReportLoggingInitializer :
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2018-05-05 13:38:10.575 ERROR 7568 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Cannot determine embedded database driver class for database type NONE
Action:
If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
Process finished with exit code 1
以上错误是由于引入mysql、jdbc驱动,springboot在启动时默认加载数据库连接,而配置文件中还没有数据库连接配置导致启动错误。
解决办法,一下提供三种方法:
1、屏蔽pom.xml文件中jdbc/mysql引入jar包后,重启项目。
2、springboot启动类增加注解,重启项目。
//启动时排除自动加载数据库连接 @EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class) @SpringBootApplication public class SpringbootJdbcApplication { public static void main(String[] args) { SpringApplication.run(SpringbootJdbcApplication.class, args); } }
3、在application.properties配置文件中增加数据库连接,重启项目。
#mysql数据连接
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
在pom.xml引入jdbc依赖包
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example.springboot</groupId> <artifactId>springboot-jdbc</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot-jdbc</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.12.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.7</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>在application.properties添加数据库连接
#修改server端口 #server.port=8085 #server.context-path=/springjdbc #mysql数据连接 spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=root #spring.datasource.max-active=20 #spring.datasource.max-idle=8 #spring.datasource.min-idle=8 #spring.datasource.initial-size=20
创建表结构
-- ---------------------------- -- Table structure for `t_user` -- ---------------------------- DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` ( `id` varchar(50) NOT NULL DEFAULT '0', `username` varchar(50) DEFAULT NULL, `password` varchar(50) DEFAULT NULL, `email` varchar(50) DEFAULT NULL, `useable` int(11) DEFAULT NULL, `addtime` varchar(50) DEFAULT NULL, `logintime` varchar(50) DEFAULT NULL, `loginip` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of t_user -- ---------------------------- INSERT INTO `t_user` VALUES ('666b477254384bcfbd54916376b75646', 'lisi', 'lisi', null, null, '2018-03-04 15:51:49', null, null); INSERT INTO `t_user` VALUES ('771f48f524ae4786aabc4a1a92ffe666', 'lisi', 'lisi', null, null, null, null, null);
编写User实体类
package com.example.springboot.jdbc.entity; import java.io.Serializable; /** * @desc用户实体类 * @Author wangsh * @date 2018/5/5 14:01 */ public class User implements Serializable { private static final long serialVersionUID = -6249397911566315813L; private Integer id; private String username; private String password;
}
编写UserDao接口
package com.example.springboot.jdbc.dao; import com.example.springboot.jdbc.entity.User; public interface UserDao { int insert(User user); int deleteById(Integer id); int update(User user); User getById(Integer id); }
编写UserDao接口实现类
package com.example.springboot.jdbc.dao.impl; import com.example.springboot.jdbc.dao.UserDao; import com.example.springboot.jdbc.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import java.sql.ResultSet; import java.sql.SQLException; /** * @desc用户操作dao * @Author wangsh * @date 2018/5/5 14:01 */ @Repository public class UserDaoImpl implements UserDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public int insert(User user) { String sql = "insert into t_user(id,username,password) values(?,?,?)"; return this.jdbcTemplate.update( sql, user.getId(), user.getUsername(), user.getPassword() ); } @Override public int deleteById(Integer id) { String sql = "delete from t_user where id = ?"; return this.jdbcTemplate.update(sql, id); } @Override public int update(User user) { String sql = "update t_user set password = ? where id = ?"; return this.jdbcTemplate.update( sql, user.getPassword(), user.getId() ); } @Override public User getById(Integer id) { String sql = "select * from t_user where id = ?"; return this.jdbcTemplate.queryForObject(sql, new RowMapper<User>() { @Override public User mapRow(ResultSet rs, int rowNum) throws SQLException { User user = new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); return user; } }, id); } }
编写UserService接口
package com.example.springboot.jdbc.service; import com.example.springboot.jdbc.entity.User; public interface UserService { int insert(User user); int deleteById(Integer id); int update(User user); User getById(Integer id); }
编写UserService接口实现类
package com.example.springboot.jdbc.service.impl; import com.example.springboot.jdbc.dao.UserDao; import com.example.springboot.jdbc.entity.User; import com.example.springboot.jdbc.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @desc用户service * @Author wangsh * @date 2018/5/5 14:01 */ @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public int insert(User user) { // 测试事物是否起作用,如果没有保存成功,则事物生效 // int a = 1/0; return userDao.insert(user); } @Override public int deleteById(Integer id) { return userDao.deleteById(id); } @Override public int update(User user) { return userDao.update(user); } @Override public User getById(Integer id) { return userDao.getById(id); } }编写controller类
package com.example.springboot.jdbc.controller; import com.example.springboot.jdbc.entity.User; import com.example.springboot.jdbc.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; import java.util.Random; /** * @desc用户操作类 * @Author wangsh * @date 2018/5/5 14:01 */ @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping("/save") @ResponseBody public User save() { User user = new User(); int id = new Random().nextInt(10000); user.setId(id); user.setUsername("张三" + id); user.setPassword("zhangsan" + id); int result = this.userService.insert(user); System.out.println(result); return user; } @RequestMapping("/getById") @ResponseBody public User getById(Integer id) { User user = this.userService.getById(id); System.out.println(user.getUsername()); return user; } @RequestMapping("/update") public void update() { User user = new User(); user.setId(1); user.setPassword("test123"); this.userService.update(user); } @RequestMapping("/deleteById") public void deleteById(Integer id) { int result = this.userService.deleteById(id); System.out.println(result); } }编写启动服务类
package com.example.springboot.jdbc; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; //启动时排除自动加载数据库连接 //@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class) @SpringBootApplication public class SpringbootJdbcApplication { public static void main(String[] args) { SpringApplication.run(SpringbootJdbcApplication.class, args); } }
完整的项目结构如下:
启动服务测试
从启动日志中可以看出,服务启动加载后的访问路径。
在浏览器中访问:http://localhost:8080/user/save
查看数据库,数据已经保存。
查询数据库测试
在浏览器中访问:http://localhost:8080/user/getById?id=8376
以上jdbc操作数据库已完成,下面介绍数据库事物管理。
service层增加事物管理
通过@Transactional注解标示那些方法需要事物管理,那些不需要,事物操作保持数据的一致性、原子性、持久性、隔离性,标示了事物的方法,操作要么成功,要么失败。
package com.example.springboot.jdbc.service.impl; import com.example.springboot.jdbc.dao.UserDao; import com.example.springboot.jdbc.entity.User; import com.example.springboot.jdbc.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * @desc用户service * @Author wangsh * @date 2018/5/5 14:01 */ @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Transactional @Override public int insert(User user) { // 测试事物是否起作用,如果没有保存成功,则事物生效 int a = 1/0; return userDao.insert(user); } @Transactional @Override public int deleteById(Integer id) { return userDao.deleteById(id); } @Transactional @Override public int update(User user) { return userDao.update(user); } @Override public User getById(Integer id) { return userDao.getById(id); } }
启动服务类,添加事物管理
package com.example.springboot.jdbc; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.transaction.annotation.EnableTransactionManagement; //启动时排除自动加载数据库连接 //@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class) //添加事物管理 @EnableTransactionManagement @SpringBootApplication public class SpringbootJdbcApplication { public static void main(String[] args) { SpringApplication.run(SpringbootJdbcApplication.class, args); } }
启动服务,测试事物操作前后数据库变化
未操作数据:
网页保存测试
访问路径: http://localhost:8080/user/save
保存出现如下错误,该错误是由于前面在service实现类中增加除0测试抛出异常信息。
操作保存后数据库,从数据库可以看出,保存出错后,数据库未插入数据,说明事物生效,异常情况下,事物自动回滚。