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());
}
});
}
}
二 SpringJdbcTemplate
<context:property-placeholder location="classpath:config.properties"/> 也可以引入
引入数据库配置文件
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config.properties</value>
</list>
</property>
</bean>
spring引入数据库配置文件
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property> <property name="maxPoolSize" value="20" />
<property name="minPoolSize" value="5" />
<property name="acquireIncrement" value="3" />
<property name="initialPoolSize" value="5"></property>
</bean>
c3p0连接池
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 初始化dataSource里面的参数 -->
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///spring3_day2"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
spring内置连接池
applicationContext注入
<bean id="baseDao" abstract="true">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
<property name="dataSource" ref="dataSource"/>
</bean>
<bean class="com.augmentum.oes.util.SpringUtil" />
其他dao 配置parent=“basedao”
web.xml监听注入
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<display-name>contextLoaderListener</display-name>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
读取applicationContext.xml 来得到相应实例的类 需先在xml中写入 <bean class="com.augmentum.oes.util.SpringUtil" />
web.xml加载会通过ApplicationContextAware接口找到他
public class SpringUtil implements ApplicationContextAware{
private static ApplicationContext applicationContext = null;
@Override
/**
* nedd set in applicationContext.xml , read the ApplicationContextAware interface
*/
public void setApplicationContext(ApplicationContext ac) throws BeansException { //beanFactory
applicationContext = ac;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String beanId) {
ApplicationContext applicationContext = getApplicationContext();
return applicationContext.getBean(beanId);
}
}
JDBCtemplete 模板的更多相关文章
- java模板和回调机制学习总结
最近看spring的JDBCTemplete的模板方式调用时,对模板和回调产生了浓厚兴趣,查询了一些资料,做一些总结. 回调函数: 所谓回调,就是客户程序C调用服务程序S中的某个函数A,然后S又在某个 ...
- Jade模板引擎让你飞
写在前面:现在jade改名成pug了 一.安装 npm install jade 二.基本使用 1.简单使用 p hello jade! 渲染后: <p>hello jade!</p ...
- ABP入门系列(2)——通过模板创建MAP版本项目
一.从官网创建模板项目 进入官网下载模板项目 依次按下图选择: 输入验证码开始下载 下载提示: 二.启动项目 使用VS2015打开项目,还原Nuget包: 设置以Web结尾的项目,设置为启动项目: 打 ...
- CMS模板应用调研问卷
截止目前,已经有数十家网站与我们合作,进行了MIP化改造,在搜索结果页也能看到"闪电标"的出现.除了改造方面的问题,MIP项目组被问到最多的就是:我用了wordpress,我用了织 ...
- PHP-自定义模板-学习笔记
1. 开始 这几天,看了李炎恢老师的<PHP第二季度视频>中的“章节7:创建TPL自定义模板”,做一个学习笔记,通过绘制架构图.UML类图和思维导图,来对加深理解. 2. 整体架构图 ...
- 【原创分享·微信支付】C# MVC 微信支付之微信模板消息推送
微信支付之微信模板消息推送 今天我要跟大家分享的是“模板消息”的推送,这玩意呢,你说用途嘛,那还是真真的牛逼呐.原因在哪?就是因为它是依赖微信生存的呀,所以他能不 ...
- OpenCV模板匹配算法详解
1 理论介绍 模板匹配是在一幅图像中寻找一个特定目标的方法之一,这种方法的原理非常简单,遍历图像中的每一个可能的位置,比较各处与模板是否“相似”,当相似度足够高时,就认为找到了我们的目标.OpenCV ...
- 前端MVC学习总结(一)——MVC概要与angular概要、模板与数据绑定
一.前端MVC概要 1.1.库与框架的区别 框架是一个软件的半成品,在全局范围内给了大的约束.库是工具,在单点上给我们提供功能.框架是依赖库的.AngularJS是框架而jQuery则是库. 1.2. ...
- ThinkPHP+Smarty模板中截取包含中英文混合的字符串乱码的解决方案
好几天没写博客了,其实有好多需要总结的,因为最近一直在忙着做项目,但是困惑了几天的Smarty模板中截取包含中英文混合的字符串乱码的问题,终于解决了,所以记录下来,需要的朋友看一下: 出现乱码的原因: ...
随机推荐
- 以8位并行数据为例确定crc-32的一般矩阵表示形式
在进行数据校验时我们会使用到crc(循环冗余校验)校验的方式,例如在以太网通信网络中会对信息进行编码和校验,生成码采用的就是33位的 crc-32:x32+x26+x23+...+x2+x+1; (1 ...
- gopub自动化发布平台安装
1.软件配置 centos7 mysql5.7.26 gopub1.1.3 2.硬件配置 4核8G aws rds aws 3.数据库配置 #这个不执行,执行下面一句 --CREATE DATABAS ...
- Irrlicht引擎剖析一
代码风格: 1.接口以I开头,实现以C开头,保存数据的结构体以S开头 2.函数名以小写字母开头,变量以大字母开头 3.接口的公共函数,其参数大部分给了默认值 4.采用名字空间 名字空间i ...
- MONGODB 数据库回复备份
1.导出工具:mongoexport 1.概念: mongoDB中的mongoexport工具可以把一个collection导出成JSON格式或CSV格式的文件.可以通过参数指 ...
- Jenkins 插件加速下载
本文主旨 看到好多加速Jenkins安装插件速度的文章,大多数教程中都是在插件配置里使用 https://mirrors.tuna.tsinghua.edu.cn/jenkins/updates/up ...
- Hadoop环境搭建|第三篇:spark环境搭建
一.环境搭建 1.1.上传spark安装包 创建文件夹用于存放spark安装文件命令:mkdir spark 1.2.解压spark安装包 命令:tar -zxvf spark-2.1.0-bin-h ...
- COM 基础 之 三大基础接口
摘自 http://blog.csdn.net/liang4/article/details/7530512 1 COM组件实际上是一个C++类,而接口都是纯虚类.组件从接口派生而来. 2 COM组件 ...
- Airbnb架构要点分享——阅读心得
目前,Airbnb已经使用了大约5000个AWS EC2实例,其中大约1500个实例用于部署其应用程序中面向Web的部分,其余的3500个实例用于各种分析和机器学习算法.而且,随着Airbnb的发展, ...
- hibernate-validator校验框架学习
1.引入jar包 <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate ...
- git提交异常 fatal: LF would be replaced by..
git提交代码时,一直报出“fatal: LF would be replaced by CRLF in (文件名)”的异常,导致代码提交不到远程仓储.其实是,不同系统对换行符的解释不同导致的. 方法 ...