JDBCtemplete 模板

package com.augmentum.oes.common;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.augmentum.oes.exception.DBException;
import com.augmentum.oes.util.DBUtil;

public class JDBCTemplete<T> {

    public List<T> query(String sql, JDBCCallback <T> jdbccallbaclk) {
        Connection conn =null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        List<T> data = new ArrayList<T>();
        boolean needMyClose = false;
        try {
          ConnectionHolder   connectionHolder = (ConnectionHolder) AppContext.getAppContext().getObject("APP_REQUEST_THREAD_CONNECTION");
              if (connectionHolder != null) {
                  conn = connectionHolder.getConn();
              }
             if (conn == null) {
                 conn = DBUtil.getConnection();
                 needMyClose = true;
             }

            stmt = conn.prepareStatement(sql);
            jdbccallbaclk.setParams(stmt);
            rs = stmt.executeQuery();
            while (rs.next()) {
                T object = jdbccallbaclk.rsToObject(rs);
                data.add(object);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new DBException();
        } finally {
            DBUtil.close(null, stmt, rs);
            if (needMyClose) {
                DBUtil.close(conn, null, null);
            }
        }
        return data;
    }

    public int insert(String sql, JDBCCallback<T> jdbcCallback) {
        Connection conn =null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        int id = 0;
        boolean needMyClose = false;
        try {
          ConnectionHolder   connectionHolder = (ConnectionHolder) AppContext.getAppContext().getObject("APP_REQUEST_THREAD_CONNECTION");
              if (connectionHolder != null) {
                  conn = connectionHolder.getConn();
              }
             if (conn == null) {
                 conn = DBUtil.getConnection();
                 needMyClose = true;
             }
             stmt = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
             jdbcCallback.setParams(stmt);
             stmt.executeUpdate();

             rs = stmt.getGeneratedKeys();
             if (rs.next()) {
                 id = rs.getInt(1);
             }
           } catch (Exception e) {
             e.printStackTrace();
             throw new DBException();
           } finally {
              DBUtil.close(null, stmt, null);
              if (needMyClose) {
                  DBUtil.close(conn, null, null);
              }
           }
        return id;
    };

    public void insertWithoutKey(String sql, JDBCCallback<T> jdbcCallback) {
        Connection conn =null;
        PreparedStatement stmt = null;
        boolean needMyClose = false;
        try {
          ConnectionHolder   connectionHolder = (ConnectionHolder) AppContext.getAppContext().getObject("APP_REQUEST_THREAD_CONNECTION");
              if (connectionHolder != null) {
                  conn = connectionHolder.getConn();
              }
             if (conn == null) {
                 conn = DBUtil.getConnection();
                 needMyClose = true;
             }
            stmt = conn.prepareStatement(sql);
            jdbcCallback.setParams(stmt);
            stmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
            throw new DBException();
        } finally {
            DBUtil.close(null, stmt, null);
            if (needMyClose) {
                DBUtil.close(conn, null, null);
            }
        }
    };

    public T QueryOne(String sql, JDBCCallback<T> jdbcCallback) {
       List<T> data = query(sql, jdbcCallback);

       if (data !=null && !data.isEmpty()) {
           return data.get(0);
       } else {
           return null;
       }
    }

    public int update(String sql,JDBCCallback<T> jdbcCallback) {
        Connection conn =null;
        PreparedStatement stmt = null;
        int count = 0;
        boolean needMyClose = false;
        try {
          ConnectionHolder   connectionHolder = (ConnectionHolder) AppContext.getAppContext().getObject("APP_REQUEST_THREAD_CONNECTION");
              if (connectionHolder != null) {
                  conn = connectionHolder.getConn();
              }
             if (conn == null) {
                 conn = DBUtil.getConnection();
                 needMyClose = true;
             }
             stmt = conn.prepareStatement(sql);
             jdbcCallback.setParams(stmt);
             count = stmt.executeUpdate();
           } catch (Exception e) {
             e.printStackTrace();
             throw new DBException();
           } finally {
              DBUtil.close(null, stmt, null);
              if (needMyClose) {
                  DBUtil.close(conn, null, null);
              }
           }
        return count;
    }

    public int deleteByid(String sql, JDBCCallback<T> jdbcCallback) {
        Connection conn =null;
        PreparedStatement stmt = null;
        int count = 0;
        boolean needMyClose = false;
        try {
          ConnectionHolder   connectionHolder = (ConnectionHolder) AppContext.getAppContext().getObject("APP_REQUEST_THREAD_CONNECTION");
              if (connectionHolder != null) {
                  conn = connectionHolder.getConn();
              }
             if (conn == null) {
                 conn = DBUtil.getConnection();
                 needMyClose = true;
             }
             stmt = conn.prepareStatement(sql);
             jdbcCallback.setParams(stmt);
             count = stmt.executeUpdate();
           } catch (Exception e) {
             e.printStackTrace();
             throw new DBException();
           } finally {
              DBUtil.close(null, stmt, null);
              if (needMyClose) {
                  DBUtil.close(conn, null, null);
              }
           }
        return count;
    }

    public int getCount(String sql,JDBCCallback<T> jdbcCallback) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        int count =0;
        boolean needMyClose = false;
        try {
          ConnectionHolder   connectionHolder = (ConnectionHolder) AppContext.getAppContext().getObject("APP_REQUEST_THREAD_CONNECTION");
              if (connectionHolder != null) {
                  conn = connectionHolder.getConn();
              }
             if (conn == null) {
                 conn = DBUtil.getConnection();
                 needMyClose = true;
             }
            stmt = conn.prepareStatement(sql);
            jdbcCallback.setParams(stmt);
            rs = stmt.executeQuery();
            if (rs.next()) {
                count = rs.getInt(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new DBException();
        } finally {
            DBUtil.close(null, stmt, rs);
            if (needMyClose) {
                DBUtil.close(conn, null, null);
            }
        }
        return count;
    }

    public int getCountAll(String sql) {
        return this.getCount(sql, new JDBCAbstractCallback<T>() {});
    }
}

JDBCTemplete

package com.augmentum.oes.common;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public interface JDBCCallback<T> {

    T rsToObject(ResultSet rs) throws SQLException;

    void setParams(PreparedStatement stmt) throws SQLException;

}

  加入数据

package com.augmentum.oes.dao.impl;

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

import org.springframework.jdbc.core.JdbcTemplate;

import com.augmentum.oes.common.JDBCAbstractCallback;
import com.augmentum.oes.common.JDBCCallback;
import com.augmentum.oes.dao.QuestionDao;
import com.augmentum.oes.model.Question;
import com.augmentum.oes.util.Pagination;
import com.augmentum.oes.util.StringUtil;

public class QuestionDaoImpl implements QuestionDao{

    private Question rsToQuestion(ResultSet rs) throws SQLException {
        Question question = new Question();
        question.setId(rs.getInt("id"));
        question.setQuestion_desc(rs.getString("question_desc"));
        question.setRight_choice_name(rs.getString("right_choice_name"));
        question.setChoice_a(rs.getString("choice_a"));
        question.setChoice_b(rs.getString("choice_b"));
        question.setChoice_c(rs.getString("choice_c"));
        question.setChoice_d(rs.getString("choice_d"));
        question.setQuestion_status(rs.getInt("question_status"));
        return question;
    }

    private JdbcTemplate jdbcTemplate;

    @Override
    public Question queryById(final int question_id){
        String sql = "SELECT * FROM question where id = ?" ;
        JDBCCallback<Question> j = new JDBCAbstractCallback<Question>() {
            @Override
            public void setParams(PreparedStatement stmt) throws SQLException {
                stmt.setInt(1, question_id);
                super.setParams(stmt);
            }

            @Override
             public Question rsToObject(ResultSet rs) throws SQLException {
                 return rsToQuestion(rs);
            }
        };
        List<Question> list = jdbcTemplete.query(sql,j);
        return list.get(0);
    }

    @Override
    public int update(final Question question) {
        String sql = "UPDATE question SET question_desc=?,right_choice_name=?,"
                + "choice_a=?, choice_b=?,choice_c=?,choice_d=?,question_status=? WHERE id = ?  ";
        int count =jdbcTemplete.update(sql, new JDBCAbstractCallback<Question>() {

            @Override
            public void setParams(PreparedStatement stmt) throws SQLException {
                stmt.setString(1, question.getQuestion_desc());
                stmt.setString(2, question.getRight_choice_name());
                stmt.setString(3, question.getChoice_a());
                stmt.setString(4, question.getChoice_b());
                stmt.setString(5, question.getChoice_c());
                stmt.setString(6, question.getChoice_d());
                stmt.setInt(7, question.getQuestion_status());
                stmt.setInt(8, question.getId());

            }
        });
        return count;
    }

    @Override
    public List<Question> getListByKeyWord(final String keyword, Pagination pagination,String orderTags) {
        pagination.setTotalCount(this.getCount(keyword));

        if (pagination.getCurrentPage() > pagination.getTotalCount()) {
            pagination.setCurrentPage(pagination.getTotalCount());
        }
        String sql ="SELECT * FROM question WHERE question_status = 0 AND question_desc LIKE ? ORDER BY id "+(StringUtil.isEmpty(orderTags)?"ASC":"DESC")+" LIMIT "+pagination.getOffset()+","+pagination.getPageSize() ;
        List<Question> list = jdbcTemplete.query(sql, new JDBCAbstractCallback<Question>() {
            @Override
            public void setParams(PreparedStatement stmt) throws SQLException {
                stmt.setString(1,"%"+keyword+"%");
            }
            @Override
            public Question rsToObject(ResultSet rs) throws SQLException {

                return rsToQuestion(rs);
            }
        });
        return list;
    }

    @Override
    public List<Question> getList(Pagination pagination,String orderTags) {
        pagination.setTotalCount(this.getCount(null));
        if (pagination.getCurrentPage() > pagination.getTotalCount()) {
            pagination.setCurrentPage(pagination.getTotalCount());
        }
        String sql ="SELECT * FROM question WHERE question_status = 0 ORDER BY id "+(StringUtil.isEmpty(orderTags)?"ASC":"DESC")+" LIMIT "+pagination.getOffset()+","+pagination.getPageSize() ;
        List<Question> list = jdbcTemplete.query(sql, new JDBCAbstractCallback<Question>() {

            @Override
            public Question rsToObject(ResultSet rs) throws SQLException {
                return rsToQuestion(rs);
            }
        });
        return list;
    }

    @Override
    public int deleteById(final int id) {
       // String sql = "DELETE FROM question where id = ?";
        String sql = "UPDATE question SET question_status=1 WHERE id= ?";
        int count = jdbcTemplete.deleteByid(sql, new JDBCAbstractCallback<Question>() {
            @Override
            public void setParams(PreparedStatement stmt) throws SQLException {
                stmt.setInt(1, id);
            }
        });
        return count;
    }

    @Override
    public int getCount(final String question_desc) {
        int count =0;
        String sql = "SELECT count(*) FROM question WHERE question_status = 0";
        if (StringUtil.isEmpty(question_desc)) {
            count = jdbcTemplete.getCountAll(sql);
        } else {
            sql = sql +" where question_desc LIKE ?";
            count = jdbcTemplete.getCount(sql, new JDBCAbstractCallback<Question>() {
            @Override
            public void setParams(PreparedStatement stmt) throws SQLException {
                stmt.setString(1,"%"+question_desc+"%");
                super.setParams(stmt);
            }
            });
        }

        return count;
    }

    @Override
    public int getNextId() {
        int nextId = 0;
        String sql = "SELECT max(id) FROM question";
        nextId = jdbcTemplete.getCountAll(sql);
        return nextId;
    }

    @Override
    public void addUpdate(final Question question) {
        String sql = "INSERT INTO question(question_status) VALUES (?)";
         jdbcTemplete.insert(sql, new JDBCAbstractCallback<Question>() {

             @Override
             public void setParams(PreparedStatement stmt) throws SQLException {
                 stmt.setInt(1, question.getQuestion_status());
             }
         });
    }
}

时间: 2024-10-25 01:28:47

JDBCtemplete 模板的相关文章

Vue.js项目模板搭建

前言 从今年(2017年)年初起,我们团队开始引入「Vue.js」开发移动端的产品.作为团队的领头人,我的首要任务就是设计 整体的架构 .一个良好的架构必定是具备丰富的开发经验后才能搭建出来的.虽然我有多年的前端开发经验,但就「Vue.js」来说,仍然是个新手.所幸「Vue.js」有一个配套工具「Vue-CLI」,它提供了一些比较成熟的项目模板,很大程度上降低了上手的难度.然而,很多具体的问题还是要自己思考和解决的. 项目划分 我们公司的H5产品大部分是嵌套在手机客户端里面的页面.每个项目的功能

ac自动机基础模板(hdu2222)

In the modern time, Search engine came into the life of everybody like Google, Baidu, etc. Wiskey also wants to bring this feature to his image retrieval system. Every image have a long description, when users type some keywords to find the image, th

hdu 2966 In case of failure kdtree模板题

问求每个点距离平方的最小的点 kd-tree模板题…… 1 #include<bits/stdc++.h> 2 #define cl(a,b) memset(a,b,sizeof(a)) 3 #define debug(x) cerr<<#x<<"=="<<(x)<<endl 4 using namespace std; 5 typedef long long ll; 6 typedef pair<int,int>

eclipse添加xml模板

//因为学javaee,中框架,,感觉配置文件好多, window-preferences-xml-xmlfiles-editor-templates-选中模板,-edit

POJ3528 HDU3662 三维凸包模板

POJ3528 HDU3662 第一道题 给定若干点 求凸包的表面积,第二题 给定若干点就凸包的面数. 简单说一下三维凸包的求法,首先对于4个点假设不共面,确定了唯一四面体,对于一个新的点,若它不在四面体内,为了让它进入凸包, 则对于所有凸包上的边,若边的一面是该点可以看到的而另一面看不到,则该点与该边构成的面要加入凸包. 模板代码非常清晰, #include<stdio.h> #include<algorithm> #include<string.h> #includ

zabbix用自带的模板监控mysql

先看一下zabbix自带的mysql模板监控项: #很少是吧,没事生产环境一般我们不用,下一篇将介绍生产环境用的另一种mysql监控. 配置zabbix自带的模板监控mysql数据库:

小程序砸金蛋、外卖模板上线啦,快到酷客多商户后台更新!

最近,微信小程序官方发文不断,又开放十几项接口,逐步给企业主带来跟多福利.于此同时,酷客多研发团队也保持着一贯的研发和版本迭代速度,此次版本主要新增幸运砸金蛋.外卖模板.意见反馈三个模块 1.新增幸运砸金蛋,大奖中不停 通过此功能可增加平台趣味性,增强用户粘性,刺激用户二次消费,是与用户互动的一大利器. 2新增外卖模板,外卖送起来 此模板是餐饮企业的福利,可在注册或者酷客多商户管理后台直接选择此模板,瞬间让您的小程序首页变的高大上,从此再也不用担心第三方外卖平台高额的佣金和账期了,因为酷客多只提

C++学习笔记50:队列类模板

队列是只能向一端添加元素,从另一端删除元素的线性群体 循环队列 在想象中将数组弯曲成环形,元素出队时,后继元素不移动,每当队尾达到数组最后一个元素时,便再回到数组开头. 队列类模板 //Queue.h #ifndef QUEUE_H #define QUEUE_H #include <cassert> //类模板的定义 template <class T, int SIZE = 50> class Queue { private: int front, rear, count; T

ReactJS React+Redux+Router+antDesign通用高效率开发模板,夜间模式为例

工作比较忙,一直没有时间总结下最近学习的一些东西,为了方便前端开发,我使用React+Redux+Router+antDesign总结了一个通用的模板,这个技术栈在前端开发者中是非常常见的. 总的来说,我这个工程十分便捷,对于初学者来说,可能包含到以下的一些知识点: 一.React-Router的使用 Router是为了方便管理组件的路径,它使用比较简单,一般定义如下就行,需要注意的是,react-router的版本有1.0-3.0,各个版本对应的API大致相似,但也有不同,我使用的是2.X的,