spring boot與jdbcTemplate的整合案例2


簡單入門了spring boot后,接下來寫寫跟數據庫打交道的案例。博文采用spring的jdbcTemplate工具類與數據庫打交道。

     下面是搭建的springbootJDBC的項目的總體架構圖:

 

<?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</groupId>  
    <artifactId>demo</artifactId>  
    <version>0.0.1-SNAPSHOT</version>  
    <packaging>jar</packaging>  
  
    <name>demo</name>  
    <description>Demo project for Spring Boot</description>  
  
    <parent>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-parent</artifactId>  
        <version>1.5.2.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.8</java.version>  
    </properties>  
  
    <dependencies>  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-web</artifactId>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-starter-jdbc</artifactId>  
        </dependency>  
  
        <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>  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-test</artifactId>  
        </dependency>  
        <dependency>  
            <groupId>com.google.guava</groupId>  
            <artifactId>guava</artifactId>  
            <version>18.0</version>  
        </dependency>  
    </dependencies>  
  
    <!--spring boot maven插件-->  
    <build>  
        <plugins>  
            <plugin>  
                <groupId>org.springframework.boot</groupId>  
                <artifactId>spring-boot-maven-plugin</artifactId>  
            </plugin>  
        </plugins>  
    </build>  
  
</project>  

  接下來,貼出application.properties,設置tomcat端口號,數據庫鏈接相關信息:

 可以參照上一篇博文,參考參考如何建立一個spring boot項目,至於在選擇依賴的配置時候,可以參考我下面貼出的pom.xml:

###### 設置tomcat訪問端口號 ######  
server.port=8088  
  
###### 設置數據源 ######  
spring.datasource.url=jdbc:mysql://localhost:3306/db_springboot?autoReconnect=true&useUnicode=true&characterEncoding=utf-8  
spring.datasource.username=root  
spring.datasource.password=123456  
spring.datasource.driver-class-name=com.mysql.jdbc.Driver  
#spring.datasource.driverClassName = com.mysql.jdbc.Driver  

 建立數據庫tb_springboot,然后執行下面的sql腳本,生成users表:

/*  
Navicat MySQL Data Transfer  
  
Source Server         : localhost  
Source Server Version : 50625  
Source Host           : localhost:3306  
Source Database       : db_springboot  
  
Target Server Type    : MYSQL  
Target Server Version : 50625  
File Encoding         : 65001  
  
Date: 2017-03-31 15:01:08  
*/  
  
SET FOREIGN_KEY_CHECKS=0;  
  
-- ----------------------------  
-- Table structure for users  
-- ----------------------------  
DROP TABLE IF EXISTS `users`;  
CREATE TABLE `users` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `name` varchar(255) DEFAULT NULL,  
  `email` varchar(255) DEFAULT NULL,  
  PRIMARY KEY (`id`)  
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;  
  
-- ----------------------------  
-- Records of users  
-- ----------------------------  
INSERT INTO `users` VALUES ('1', 'linsen', 'linsen@126.com');  
INSERT INTO `users` VALUES ('2', 'sam', 'sam@qq.com');  
INSERT INTO `users` VALUES ('3', 'debug', 'debug@sina.com');  
INSERT INTO `users` VALUES ('4', '傑克', '傑克@sina.com');  
INSERT INTO `users` VALUES ('5', '張三', '張三@sina.com');  
INSERT INTO `users` VALUES ('6', '李四', '李四@sina.com');  
INSERT INTO `users` VALUES ('7', '王五', '王五@sina.com');  
INSERT INTO `users` VALUES ('8', '王五2', '王五2@sina.com');  

   本博文我們對spring boot與jdbcTemplate進行整合,主要當然是實現基本的 增刪改查 user實體 操作,首先是開發dao層:

package com.example.repository;  
  
import com.example.entity.User;  
import com.example.exception.UserException;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.jdbc.core.JdbcTemplate;  
import org.springframework.jdbc.core.PreparedStatementCreator;  
import org.springframework.jdbc.core.PreparedStatementSetter;  
import org.springframework.jdbc.core.RowMapper;  
import org.springframework.jdbc.support.GeneratedKeyHolder;  
import org.springframework.jdbc.support.KeyHolder;  
import org.springframework.stereotype.Repository;  
import org.springframework.transaction.annotation.Transactional;  
  
import java.sql.Connection;  
import java.sql.PreparedStatement;  
import java.sql.ResultSet;  
import java.sql.SQLException;  
import java.util.ArrayList;  
import java.util.List;  
  
/** 
 * Created by steadyjack on 2017/3/22. 
 * 充當dao層UserRepository 
 */  
@Repository  
public class UserRepository {  
  
    @Autowired  
    private JdbcTemplate jdbcTemplate;  
  
    /** 
     * 獲取用戶列表 
     * @return 
     * @throws Exception 
     */  
    @Transactional(readOnly = true)  
    public List<User> getUserList() throws Exception{  
        List<User> userList=jdbcTemplate.query("select id,name,email from users",new UserRowMapper());  
        System.out.println(userList);  
        return userList;  
    }  
  
    /** 
     * 根據用戶id獲取用戶 
     * @param id 
     * @return 
     * @throws Exception 
     */  
    @Transactional(readOnly = true)  
    public User getUserById(Integer id) throws  Exception{  
        //queryForObject:找不到會報異常  query:找不到則Null  
        //User user=jdbcTemplate.queryForObject("select id,name,email from users where id=?",new Object[]{id},new UserRowMapper());  
        List<User> userList=jdbcTemplate.query("select id,name,email from users where id=?",new Object[]{id},new UserRowMapper());  
        User user=null;  
        if (!userList.isEmpty()){  
            user=userList.get(0);  
        }  
        System.out.println(user);  
        return user;  
    }  
  
    /** 
     * 插入用戶數據 
     * @param user 
     * @return 
     * @throws Exception 
     */  
    public int saveUser(final User user) throws  Exception{  
        int resRow=jdbcTemplate.update("INSERT INTO users(id,name,email) VALUES(NULL,?,?)",new Object[]{  
           user.getName(),user.getEmail()  
        });  
        System.out.println("操作結果記錄數:  "+resRow);  
        return resRow;  
    }  
  
    /** 
     * 插入用戶數據-防止sql注入 
     * @param user 
     * @return 
     * @throws Exception 
     */  
    public int saveUserWithSafe(final User user) throws  Exception{  
        int resRow=jdbcTemplate.update("INSERT INTO users(id,name,email) VALUES(NULL,?,?)", new PreparedStatementSetter() {  
            @Override  
            public void setValues(PreparedStatement ps) throws SQLException {  
                ps.setString(1,user.getName());  
                ps.setString(2,user.getEmail());  
            }  
        });  
        System.out.println("操作結果記錄數:  "+resRow);  
        return resRow;  
    }  
  
    /** 
     * 插入用戶數據-防止sql注入-可以返回該條記錄的主鍵(注意需要指定主鍵) 
     * @param user 
     * @return 
     * @throws Exception 
     */  
    @Transactional(rollbackFor=UserException.class)  
    public int saveUserWithKey(final User user) throws  Exception{  
        String sql="INSERT INTO users(id,name,email) VALUES(NULL,?,?)";  
        KeyHolder keyHolder=new GeneratedKeyHolder();  
        int resRow=jdbcTemplate.update(new PreparedStatementCreator() {  
            @Override  
            public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {  
                PreparedStatement ps=conn.prepareStatement(sql,new String[]{"id"}); //指定 id 為主鍵  
                ps.setString(1,user.getName());  
                ps.setString(2,user.getEmail());  
                return ps;  
            }  
        },keyHolder);  
        System.out.println("操作結果記錄數:  "+resRow+" 主鍵: "+keyHolder.getKey());  
        return Integer.parseInt(keyHolder.getKey().toString());  
    }  
  
    /** 
     * 更新用戶信息 
     * @param user 
     * @return 
     */  
    public int updateUser(final User user) throws  Exception{  
        String sql="update users set name=?,email=? where id=?";  
        int resRow=jdbcTemplate.update(sql, new PreparedStatementSetter() {  
            @Override  
            public void setValues(PreparedStatement preparedStatement) throws SQLException {  
                preparedStatement.setString(1,user.getName());  
                preparedStatement.setString(2,user.getEmail());  
                preparedStatement.setInt(3,user.getId());  
            }  
        });  
        System.out.println("操作結果記錄數:  "+resRow);  
        return resRow;  
    }  
  
    /** 
     * 刪除用戶 
     * @param user 
     * @return 
     * @throws Exception 
     */  
    public int deleteUser(final User user) throws  Exception{  
        int resRow=jdbcTemplate.update("DELETE FROM users WHERE id=?", new PreparedStatementSetter() {  
            @Override  
            public void setValues(PreparedStatement ps) throws SQLException {  
                ps.setInt(1,user.getId());  
            }  
        });  
        System.out.println("操作結果記錄數:  "+resRow);  
        return resRow;  
    }  
  
    /** 
     * 根據用戶名查找用戶-用於判斷用戶是否存在 
     * @param user 
     * @return 
     * @throws Exception 
     */  
    public User getUserByUserName(final User user) throws Exception{  
        String sql="select id,name,email from users where name=?";  
        List<User> queryList=jdbcTemplate.query(sql,new UserRowMapper(),new Object[]{user.getName()});  
        if (queryList!=null && queryList.size()>0){  
            return queryList.get(0);  
        }else{  
            return null;  
        }  
    }  
  
    /** 
     * 獲取記錄數 
     * @return 
     * @throws Exception 
     */  
    public Integer getCount() throws  Exception{  
        String sql="select count(id) from users";  
        //jdbcTemplate.getMaxRows();  
        Integer total=jdbcTemplate.queryForObject(sql,Integer.class);  
        System.out.println("操作結果記錄數:  "+total);  
        return total;  
    }  
  
    //其他的像模糊查詢之類的可以自己嘗試查查 jdbcTemplate 的使用文檔  
  
  
}  
  
/** 
 * 行映射 
 */  
class UserRowMapper implements RowMapper<User>{  
  
    @Override  
    public User mapRow(ResultSet resultSet, int i) throws SQLException {  
        User user=new User();  
        user.setId(resultSet.getInt("id"));  
        user.setName(resultSet.getString("name"));  
        user.setEmail(resultSet.getString("email"));  
        return user;  
    }  
  
}  

代碼以及相關的注釋我已經寫在里面了,個人覺得很清晰了,如果有啥問題,可以下面留言,或者后面提到的技術交流群交流。

    接下來,當然是開發controller層,在這里,我主要開發rest服務接口,結果將以json的格式返回給發起請求的客戶端(以postman進行模擬),下面是我的restController:

package com.example.controller;  
  
import com.example.DemoApplication;  
import com.example.entity.User;  
import com.example.repository.UserRepository;  
import com.google.common.base.Strings;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.boot.test.context.SpringBootTest;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.bind.annotation.RestController;  
  
import javax.servlet.http.HttpServletRequest;  
import java.util.List;  
  
/** 
 * Created by steadyjack on 2017/3/22. 
 */  
@SpringBootTest(classes = DemoApplication.class)  
@RestController  
@RequestMapping("/user")  
public class UserController {  
  
    @Autowired  
    private UserRepository userRepository;  
  
    /** 
     * 用戶列表 
     * @return 
     */  
    @RequestMapping("/list")  
    public List<User> listUser() {  
        List<User> userList=null;  
        try {  
            userList=userRepository.getUserList();  
        }catch (Exception e){  
            System.out.println("異常信息:  "+e.getMessage());  
        }  
        return userList;  
    }  
  
    /** 
     * 根據id查詢User實體 
     * @param id 
     * @return 
     */  
    @RequestMapping("/{id}")  
    public User getUserById(@PathVariable Integer id){  
        User user=null;  
        try {  
            user=userRepository.getUserById(id);  
        }catch (Exception e){  
            user=new User(1,"admin","admin@sina.com");  
            System.out.println("異常信息: "+e.getMessage());  
        }  
        return user;  
    }  
  
    /** 
     * 保存user實體 
     * @param user 
     * @return 
     */  
    @RequestMapping(value = "/save",method = RequestMethod.POST)  
    public int insertUser(User user){  
        int res=1;  
        try {  
            res=userRepository.saveUser(user);  
        }catch (Exception e){  
            System.out.println("異常信息: "+e.getMessage());  
        }  
        return res;  
    }  
  
    /** 
     * 保存User實體-PreparedStatementSetter 
     * @param user 
     * @return 
     */  
    @RequestMapping(value = "/saveWithSafe",method = RequestMethod.POST)  
    public int insertUserWithSafe(User user){  
        int res=1;  
        try {  
            res=userRepository.saveUserWithSafe(user);  
        }catch (Exception e){  
            System.out.println("異常信息: "+e.getMessage());  
        }  
        return res;  
    }  
  
    /** 
     * 保存user實體-PreparedStatementCreator、KeyHolder-保存實體后返回實體的主鍵 
     * @param user 
     * @return 
     */  
    @RequestMapping(value = "/saveWithKey",method = RequestMethod.POST)  
    public int insertUserWithKey(User user){  
        int res=1;  
        try {  
            res=userRepository.saveUserWithKey(user);  
        }catch (Exception e){  
            System.out.println("異常信息: "+e.getMessage());  
        }  
        return res;  
    }  
  
    /** 
     * 根據id更新user實體 
     * @param id 
     * @param request 
     * @return 
     */  
    @RequestMapping(value = "/update/{id}",method = RequestMethod.POST)  
    public int updateUserWithId(@PathVariable Integer id,HttpServletRequest request){  
        int res=1;  
        try {  
            if (id!=null && !id.equals(0)){  
                String name=request.getParameter("name");  
                String email=request.getParameter("email");  
                User updateUser=new User(id, Strings.isNullOrEmpty(name)?null:name,Strings.isNullOrEmpty(email)?null:email);  
                res=userRepository.updateUser(updateUser);  
            }  
        }catch (Exception e){  
            System.out.println("異常信息: "+e.getMessage());  
        }  
        return res;  
    }  
  
    /** 
     * 根據id刪除user實體 
     * @param id 
     * @return 
     */  
    @RequestMapping("/delete/{id}")  
    public int deleteUserById(@PathVariable Integer id){  
        int res=1;  
        try {  
            User deleteUser=userRepository.getUserById(id);  
            res=userRepository.deleteUser(deleteUser);  
        }catch (Exception e){  
            System.out.println("異常信息: "+e.getMessage());  
        }  
        return res;  
    }  
  
    /** 
     * 根據name查詢是否存在某個user實體 
     * @param request 
     * @return 
     */  
    @RequestMapping("/isExistUser")  
    public Boolean isExistUser(HttpServletRequest request){  
        Boolean res=false;  
        try {  
            String name=request.getParameter("name");  
            User queryUser=new User(null,Strings.isNullOrEmpty(name)?null:name,null);  
            User deleteUser=userRepository.getUserByUserName(queryUser);  
            if (deleteUser!=null){  
                res=true;  
            }  
        }catch (Exception e){  
            System.out.println("異常信息: "+e.getMessage());  
        }  
        return res;  
    }  
  
    /** 
     * 查詢user實體的總數 
     * @return 
     */  
    @RequestMapping("/total")  
    public Integer getTotal(){  
        Integer res=0;  
        try {  
            res=userRepository.getCount();  
        }catch (Exception e){  
            System.out.println("異常信息: "+e.getMessage());  
        }  
        return res;  
    }  
  
}  

 至此已經開發完畢了,你可以直接run DemoApplication類,然后在瀏覽器測試訪問,也可以在postman發起訪問!下面我才用一鍵式部署到我的本地tomcat服務器:

   

 

 

    完了之后,(當然啦,你也可以jar -jar將你的spring boot打包為jar項目,然后$ java –jar E:\IDEA_Workspace\springbootJDBC\target\demo-0.0.1-SNAPSHOT.jar 也可以直接跑起來)

    好了,現在默認就是啟動了這個sb項目,下面就開始訪問測試各個服務(開頭都以 127.0.0.1:8088/)

    1,首先是獲取用戶列表:

   

   2、接着是查詢id=3 的user實體:

 

   3、將id=3的實體刪除(1:代表操作的記錄數-說明已經成功刪除)

 

  4、再次查詢出來:

 

  5、增加一個user實體:

 

  6、檢驗一下是否增加該實體成功:

 

    7、更新id=11的實體的相關數據(1:代表更新成功)

 

   8、檢驗一下是否更新數據成功!

 

    好了,整合完畢!下面提供postman的下載地址(當然了,上面的那些地址其實也可以通過browser進行訪問的)

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM