springboot使用JdbcTemplate简单操作数据库,还有一些MyBatis、Hibernate、Spring Data JPA其他框架后续再研究
一、安装mysql,准备测试数据
本地安装mysql,新建数据库wx_springboot,新建表:wx_User
DROP TABLE IF EXISTS `wx_User`;
CREATE TABLE `wx_User` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '编号',
`name` varchar(25) DEFAULT NULL COMMENT '姓名',
`description` varchar(25) DEFAULT NULL COMMENT '描述',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
BEGIN;
INSERT INTO `wx_User` VALUES ('1', 'xxxx', '他在学习springboot'), ('2', 'sx', '他在学习nginx'), ('3', 'cm', '他在学习tomcat'), ('4', 'wx', '他在学习springboot');
COMMIT;
二、springboot项目配置文件:可以参考上一篇新建springboot项目:https://blog.csdn.net/wx19900503/article/details/102902780
1、增加pom依赖
org.springframework.boot
spring-boot-starter-jdbc
mysql
mysql-connector-java
runtime
2、application.properties配置mysql数据源
# mysql
spring.datasource.url=jdbc:mysql://localhost:13306/wx_springboot?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
// springboot2.0使用,之前1.5使用com.mysql.jdbc.Driver报错
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
若是改变数据库配置信息则需要自定义数据源配置:如
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource(){
return new BasicDataSource();
}
}
3、DemoControllar 新增
/**
* 返回list
**/
@GetMapping("/queryList")
public List
运行springboot,访问接口http://localhost:8080/queryList
三、上面简单就可以是用了,这边新增实体类,来完成对该表的增删改查
具体代码结构如下:
如果运行发生报错:
2019-11-01 14:09:40.361 ERROR 1737 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field userService in com.wuxi.controllar.UserControllar required a bean of type 'com.wuxi.service.UserService' that could not be found.
需要调整UserApplication类到上一层包下面
1、新增user类
/**
* @ClassName User
* @Description //TODO
* @Author wuxi
* @Date 2019-11-01 10:17
* @Version 1.0
**/
public class User {
private int id;
private String name;
private String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", description='" + description + '\'' +
'}';
}
}
2、新增UserDao层,完成对数据库的操作
/**
* @ClassName UserDao
* @Description //TODO
* @Author wuxi
* @Date 2019-11-01 11:03
* @Version 1.0
**/
@Repository
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
//使用BeanPropertyRowMapper将实体类和数据库字段自动对应
@Transactional
public List findAllUser() {
List userList = jdbcTemplate.query("select * from wx_User", new Object[]{}, new BeanPropertyRowMapper(User.class));
return userList;
}
@Transactional
public User findUserById(int id) {
List userList = jdbcTemplate.query("select * from wx_User where id = ?", new Object[]{id}, new BeanPropertyRowMapper(User.class));
User user = null;
if (!userList.isEmpty()) {
user = userList.get(0);
}
return user;
}
@Transactional
public int deleteUserById(int id) {
return jdbcTemplate.update("DELETE from wx_User where id = ? ",id);
}
@Transactional
public int updateUserById(User user) {
return jdbcTemplate.update("UPDATE wx_User SET name = ? , description = ? WHERE id=?",
user.getName(), user.getDescription(), user.getId());
}
@Transactional
public int saveOneUser(User user) {
return jdbcTemplate.update("insert into wx_User(id,name, description) values(?, ?, ?)",
user.getId(),user.getName(), user.getDescription());
}
}
3、新建UserService接口:
public interface UserService {
List findAllUser();
User findUserById(int id);
Integer saveUser(User user);
Integer updateUser(User user);
Integer deleteUser(int id);
}
新建UserServiceImpl 实现该接口:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public List findAllUser() {
return userDao.findAllUser();
}
@Override
public User findUserById(int id) {
return userDao.findUserById(id);
}
@Override
public Integer saveUser(User user) {
return userDao.saveOneUser(user);
}
@Override
public Integer updateUser(User user) {
return userDao.updateUserById(user);
}
@Override
public Integer deleteUser(int id) {
return userDao.deleteUserById(id);
}
}
编写Controllar层:
@RestController
public class UserControllar {
@Autowired
private UserService userService;
//get http://localhost:8080/user
@RequestMapping(value = "/user", method = RequestMethod.GET)
public List findAllUser() {
return userService.findAllUser();
}
//get http://localhost:8080/user/1
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public User findAllUser(@PathVariable("id") int id) {
return userService.findUserById(id);
}
//delete http://localhost:8080/user/1
@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
public void deleteUserById(@PathVariable("id") int id) {
userService.deleteUser(id);
}
//put http://localhost:8080/user
@RequestMapping(value = "/user", method = RequestMethod.PUT)
public void updateUserById(@RequestBody User user) {
userService.updateUser(user);
}
//post http://localhost:8080/user
@RequestMapping(value = "/user", method = RequestMethod.POST)
public void saveOneUser(@RequestBody User user) {
userService.saveUser(user);
}
}
简单使用浏览器测试:
其他post、put等方式请求可以用Jmeter测试验证ok