1. 程式人生 > >Spring Boot 使用JdbcTemplate操作資料庫

Spring Boot 使用JdbcTemplate操作資料庫

使用JdbcTemplate操作資料庫

配置資料來源

以MySQL作為自定義資料來源。首先在pom.xml中去除對h2的依賴。保留spring-boot-starter-data-jpa的依賴,然後增加Mysql的依賴

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<
groupId
>
mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency
>

配置資料庫相關資訊

配置application.properties配置檔案。在預設情況下,spring boot會使用其繫結的Tomcat的資料來源,我們可以對其進行設定。

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot_database
spring.datasource.username=root
spring.datasource.password=123456
# spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#最大等待連線中的數量,設定0為沒有限
spring.datasource.tomcat.max-idle=10
#最大連線活動數
spring.datasource.tomcat.max-active=50
#最大等待毫秒數,單位ms,超過時間會出錯誤資訊
spring.datasource.tomcat.max-wait=10000
#資料庫連線池初始化連線數
spring.datasource.tomcat.initial-size=5

注意這裡註釋掉了spring.datasource.driver-class-name=com.mysql.jdbc.Driver驅動類的配置,但是它還是可以連線數源的,這是因為Spring Boot會盡可能地去判斷資料來源是說明型別的,然後根據預設的情況去匹配驅動類。在它不能匹配的情況下,你可以明確的配置它,這樣就不會使用預設的驅動類了。

在配置資料來源後,Spring boot通過其自動配置機制配置好了JdbcTemplate,JdbcTemplate模板是spring框架提供的。準確的來說,JdbcTemplate這種方式不算成功,在實際工作中還是比較少使用的,更多的是Hibernate和MyBatis。所以這裡只是簡單的介紹下它使用的方法。

SQL建表

CREATE TABLE `t_user` (
  `id` int(12) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(60) NOT NULL,
   /** 性別,1-男,2-女**/ 
  `sex` int(3) NOT NULL DEFAULT '1',
  `note` varchar(256) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ;

使用者POJO

package com.lay.pojo;

public class User {
    private Long id = null;
    
    private String userName = null;
    
    private SexEnum sex = null;//列舉
    
    private String note = null;
    
    public Long getId() {
        return id;
    }
    
    public void setId(Long id) {
        this.id = id;
    }
    
    public String getUserName() {
        return userName;
    }
    
    public void setUserName(String userName) {
        this.userName = userName;
    }
    
    public SexEnum getSex() {
        return sex;
    }
    
    public void setSex(SexEnum sex) {
        this.sex = sex;
    }
    
    public String getNote() {
        return note;
    }
    
    public void setNote(String note) {
        this.note = note;
    }
    
}

其中有個性別列舉類

SexEnum

package com.lay.enumeration;

public enum SexEnum {
    MALE(1, "男"), FEMALE(2, "女");
    
    private int id;
    
    private String name;
    
    SexEnum(int id, String name) {
        this.id = id;
        this.name = name;
    }
    
    public static SexEnum getEnumById(int id) {
        for (SexEnum sex : SexEnum.values()) {
            if (sex.getId() == id) {
                return sex;
            }
        }
        return null;
    }
    
    public static SexEnum getEnumByName(String name) {
        for (SexEnum sex : SexEnum.values()) {
            if (sex.getName().equals(name)) {
                return sex;
            }
        }
        return null;
    }
    
    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;
    }
    
}

使用者服務介面

JdbcTmpUserService

package com.lay.service;

import java.util.List;

import com.lay.pojo.User;

public interface JdbcTmpUserService {
    
    public User getUser(Long id);
    
    public List<User> findUsers(String userName, String note);
    
    public int insertUser(User user);
    
    public int updateUser(User user);
    
    public int deleteUser(Long id);
    
}

實現使用者介面

JdbcTmpUserServiceImpl

package com.lay.service.impl;

import java.sql.ResultSet;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.lay.enumeration.SexEnum;
import com.lay.pojo.User;
import com.lay.service.JdbcTmpUserService;

@Service
public class JdbcTmpUserServiceImpl implements JdbcTmpUserService {
    @Autowired
    private JdbcTemplate jdbcTemplate = null;
    
    //獲取對映關係
    private RowMapper<User> getUserMapper() {
        //使用lambda表示式建立使用者對映關係
        RowMapper<User> userRowMapper = (ResultSet rs, int rownum) -> {
            User user = new User();
            user.setId(rs.getLong("id"));
            user.setUserName(rs.getString("user_name"));
            int sexId = rs.getInt("sex");
            SexEnum sex = SexEnum.getEnumById(sexId);
            user.setSex(sex);
            user.setNote(rs.getString("note"));
            return user;
        };
        return userRowMapper;
    }
    
    //獲取物件
    @Override
    public User getUser(Long id) {
        //執行sql
        String sql = "select id,user_name,sex,note from t_user where id=?";
        //引數
        Object[] params = new Object[] {id};
        User user = jdbcTemplate.queryForObject(sql, params, getUserMapper());
        return user;
    }
    
    //查詢使用者列表
    @Override
    public List<User> findUsers(String userName, String note) {
        String sql = "select id,user_name,sex,note fromt_user" + "where user_name like concat('%',?,'%')" + "and note like concat('%',?,'%')";
        //引數
        Object[] params = new Object[] {userName, note};
        List<User> userList = jdbcTemplate.query(sql, params, getUserMapper());
        return userList;
    }
    
    //插入資料庫
    @Override
    public int insertUser(User user) {
        String sql = "insert into t_user(user_name,sex,note) values(?,?,?)";
        
        return jdbcTemplate.update(sql, user.getUserName(), user.getSex().getId(), user.getNote());
    }
    
    //更新資料庫
    @Override
    public int updateUser(User user) {
        String sql = "update t_user set user_name=?,sex=?,note=?" + "where id=?";
        return jdbcTemplate.update(sql, user.getUserName(), user.getSex().getId(), user.getNote(), user.getId());
    }
    
    //刪除資料
    @Override
    public int deleteUser(Long id) {
        String sql = "delete from t_user where id=?";
        return jdbcTemplate.update(sql, id);
    }
    
}

控制器

JdbcTemplateController

package com.lay.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lay.enumeration.SexEnum;
import com.lay.pojo.User;
import com.lay.service.JdbcTmpUserService;

@RestController
@RequestMapping(value = "/user")
public class JdbcTemplateController {
    
    @Autowired
    JdbcTmpUserService userService;
    
    @RequestMapping(value = "/insert")
    public String insertUser() {
        User user = new User();
        user.setUserName("zhangsan");
        user.setSex(SexEnum.getEnumByName("男"));
        user.setNote("i love u");
        int result = userService.insertUser(user);
        return result + "";
    }
    //qi
}

測試

啟動服務,開啟瀏覽器地址輸入http://localhost:8080/user/insert