SpringBoot + JdbcTemplate实现mysql数据库访问

69 篇文章 1 订阅
21 篇文章 1 订阅

在开发服务端程序时,数据库交互是非常常见的,如果没了数据库,站点相应也就变成了静态的。从本片文章开始,我会介绍一下SpringBoot连接mysql的几种常见方式(包括使用mybatis ORM框架)。本篇文章首先介绍一下使用JdbcTemplate实现mysql数据库连接,Spring Framework在Jdbc上面做了深层次的封装,通过依赖注入功能,可以将 DataSource 注入到JdbcTemplate之中,使我们可以轻易的完成对象关系映射,并有助于规避常见的错误,在SpringBoot中我们可以很轻松的使用它。实际开发中,肯定很少有使用JdbcTemplate进行开发的,都是使用诸如Mybatis之类的ORM框架。但是JdbcTemplate作为SpringFramework固有组件,具备配置简单、访问速度快、学习成本低等特点,在不了解ORM框架的前提下,作为SpringBoot连接数据库的入门工具使用是非常合适的。

1. 项目结构

|   pom.xml
|   springboot-04-jdbctemplate.iml
|
+---src
|   +---main
|   |   +---java
|   |   |   \---com
|   |   |       \---zhuoli
|   |   |           \---service
|   |   |               \---springboot
|   |   |                   \---jdbctemplate
|   |   |                       |   SpringBootTemplateApplicationContext.java
|   |   |                       |
|   |   |                       +---controller
|   |   |                       |       UserController.java
|   |   |                       |
|   |   |                       +---repository
|   |   |                       |   +---model
|   |   |                       |   |       User.java
|   |   |                       |   |
|   |   |                       |   \---service
|   |   |                       |       |   UserRepository.java
|   |   |                       |       |
|   |   |                       |       \---impl
|   |   |                       |               UserRepositoryImpl.java
|   |   |                       |
|   |   |                       \---service
|   |   |                           |   UserControllerService.java
|   |   |                           |
|   |   |                           \---impl
|   |   |                                   UserControllerServiceImpl.java
|   |   |
|   |   \---resources
|   |           application.properties

com.zhuoli.service.springboot.jdbctemplate.controller: 对外暴露http服务接口

com.zhuoli.service.springboot.jdbctemplate.service: controller直接调用的服务层

com.zhuoli.service.springboot.jdbctemplate.repository: 数据库交互逻辑

2. 新建user表

CREATE TABLE `user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户编号',
  `user_name` varchar(25) DEFAULT NULL COMMENT '用户名称',
  `description` varchar(25) DEFAULT NULL COMMENT '描述',
  `is_deleted` tinyint(3) DEFAULT NULL COMMENT '是否删除',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

3. pom.xml添加JdbcTemplate依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

4. application.properties添加数据库连接配置

spring.datasource.url=jdbc:mysql://115.47.149.48:3306/zhuoli_test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false
spring.datasource.password=zhuoli
spring.datasource.username=zhuoli

5. 编码实现

5.1 controller定义:

@RestController
@AllArgsConstructor
@RequestMapping(value = "/user")
@Slf4j
public class UserController {

    private UserControllerService userControllerService;

    @RequestMapping(value = "/get_all", method = RequestMethod.POST)
    public ResponseEntity getAllUser() {
        return ResponseEntity.status(HttpStatus.OK).body(userControllerService.getAllUsers());
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public ResponseEntity createUser(@RequestParam(value = "userName") String userName,
                                     @RequestParam(value = "description") String description){
        User user = new User();
        user.setUserName(userName);
        user.setDescription(description);

        userControllerService.createUser(user);
        return ResponseEntity.status(HttpStatus.OK).body("create user success");
    }

    @RequestMapping(value = "/query_user", method = RequestMethod.POST)
    public ResponseEntity queryUserById(@RequestParam(value = "id") Long id){
        return ResponseEntity.status(HttpStatus.OK).body(userControllerService.getUserById(id));
    }

    @RequestMapping(value = "/update_user", method = RequestMethod.POST)
    public ResponseEntity updateUserById(@RequestParam(value = "id") Long id,
                                         @RequestParam(value = "userName") String userName,
                                         @RequestParam(value = "description") String description){
        User user = new User();
        user.setId(id);
        user.setUserName(userName);
        user.setDescription(description);
        userControllerService.updateUser(user);
        return ResponseEntity.status(HttpStatus.OK).body("update user success");
    }

    @RequestMapping(value = "/del_user", method = RequestMethod.POST)
    public ResponseEntity deleteUserById(@RequestParam(value = "id") Long id){
        userControllerService.delUserById(id);
        return ResponseEntity.status(HttpStatus.OK).body("del user success");
    }
}

5.2 service定义

public interface UserControllerService {
    List<User> getAllUsers();

    User getUserById(Long id);

    int delUserById(Long id);

    int createUser(User user);

    int updateUser(User user);
}

实现类在这就不粘贴出来了,有需要的同学可以去下载示例代码

5.3 repository定义

public interface UserRepository {
    List<User> getAllUsers();

    User getUserById(Long id);

    int delUserById(Long id);

    int createUser(User user);

    int updateUser(User user);
}

为了展示JdbcTemplate的用法,这里讲repository的实现展示一下:

@Repository
@AllArgsConstructor
public class UserRepositoryImpl implements UserRepository {
    private final JdbcTemplate jdbcTemplate;

    @Override
    public List<User> getAllUsers() {
        String sql = "select * from user";
        return jdbcTemplate.query(sql, new Object[]{}, new BeanPropertyRowMapper<>(User.class));
    }

    @Override
    public User getUserById(Long id) {
        String sql = "select * from user where id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(User.class));
    }

    @Override
    public int delUserById(Long id) {
        String sql = "UPDATE user SET is_deleted = 1 WHERE id = ?";
        return jdbcTemplate.update(sql, id);
    }

    @Override
    public int createUser(User user) {
        String sql = "insert into user(user_name, description, is_deleted) values(?, ?, 0)";
        return jdbcTemplate.update(sql, user.getUserName(), user.getDescription());
    }

    @Override
    public int updateUser(User user) {
        String sql = "UPDATE user SET user_name = ? ,description = ? WHERE id = ?";
        return jdbcTemplate.update(sql, user.getUserName(), user.getDescription(), user.getId());
    }
}

6. 测试

使用postman进行接口测试,由于controller方法参数使用的是@RequestParam接收的,所以测试时,请求头要设置为x-www-form-urlencoded,否则会报“HTTP Status 400 – Required String parameter ‘xx’ is not present”错,具体请查看

7. 总结

通过如上示例代码,可以发现,其实使用jdbcTemplate要比直接使用jdbc进行数据库连接要简单多了。对于使用Springboot这种情况,直接引入jar包,简单配置就能直接上手使用,对于没有使用过ORM框架的同学是很友好的。但是同时使用jdbcTemplate也要依赖于手写sql,对于手写sql这个东西,褒贬不一,有些人认为有极大的灵活性,有些人则认为增加了使用的复杂性,且容易写出慢查询。现在常用的ORM框架都是支持自定义sql的,但是也同时很好的支持了非原生sql操作的支持。

示例代码:码云 – 卓立 – Spring Boot + JdbcTemplate数据库访问

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值