springboot使用JdbcTemplate操作mysql数据库

新建工程

采用idea的spring boot创建向导创建web工程demo

pom依赖

<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-jdbcartifactId>
dependency>

<dependency>
    <groupId>org.projectlombokgroupId>
    <artifactId>lombokartifactId>
    <optional>trueoptional>
dependency>

application.yml配置

# 数据库url地址
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
    dbcp2:
      max-idle: 10
      max-wait-millis: 10000
      min-idle: 5
      initial-size: 5

数据库

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  `password` varchar(30) NOT NULL,
  `email` varchar(30) NOT NULL,
  `age` int(3) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

实体

package com.demo.entity;

import lombok.Data;

/**
 * @author Administrator
 * @date 2019/4/12
 */
@Data
public class User {
    private Long id;
    private String username;
    private String password;
    private String email;
    private Integer age;
}

访问controller

@RestController
public class UserController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping(value = "/user/{id}")
    public User getUser(@PathVariable("id") Long id) {
        String sql = "select * from user where id = ?";
        Object[] args = {id};
        List<User> users = jdbcTemplate.query(sql, args, (rs, i) -> {
            User user = new User();
            user.setId(rs.getLong("id"));
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setEmail(rs.getString("email"));
            user.setAge(rs.getInt("age"));
            return user;
        });
        return users.isEmpty() ? new User() : users.get(0);
    }
}

结果

访问http://localhost:8080/user/1


{"id":1,"username":"admin","password":"admin","email":"[email protected]","age":20}

你可能感兴趣的:(spring,springboot,mysql,jdbc)