[size=xx-small]前言[/size]
本来对用法不是很想总结的,因为这些东西都是拿过来用,对原理不理解的我,觉得写这些总结就和网上铺天盖地的文章一样。但是昨天写了一篇发现想用的话其中还是有那么点问题的。所以就把JDBC template的常用总结再写一遍吧。
好啦,言归正传。
JDBC 配置
jdbc.properties
# Properties file with JDBC and JPA settings.
#
# Applied by <context:property-placeholder location="jdbc.properties"/> from
# various application context XML files (e.g., "applicationContext-*.xml").
# Targeted at system administrators, to avoid touching the context XML files.
#-------------------------------------------------------------------------------
# MySQL Settings
#加载驱动
jdbc.driverClassName=com.mysql.jdbc.Driver
#指定数据库、设置字符集、编码格式、自动连接
jdbc.url=jdbc:mysql://localhost:8080/?useUnicode=true&characterEncoding=UTF8&characterSetResults=UTF8&autoReconnect=true
#数据库名字
jdbc.username=root
#数据库密码
jdbc.password=123456
#mysqlmysql\u8FDE\u63A5\u5173\u95ED c3p0\u672A\u5173\u95ED\u95EE\u9898
c3p0.minPoolSize = 1
c3p0.maxPoolSize = 50
c3p0.initialPoolSize = 1
c3p0.maxIdleTime = 25000
c3p0.acquireIncrement = 1
c3p0.acquireRetryAttempts = 30
c3p0.acquireRetryDelay = 1000
c3p0.testConnectionOnCheckin = false
#c3p0.automaticTestTable = t_c3p0
c3p0.idleConnectionTestPeriod = 18000
c3p0.checkoutTimeout=5000
# Properties that control the population of schema and data for a new data source
#jdbc.initLocation=classpath:db/mysql/initDB.txt
#jdbc.dataLocation=classpath:db/mysql/populateDB.txt
# Property that determines which Hibernate dialect to use
# (only applied with "applicationContext-hibernate.xml")
#hibernate.dialect=org.hibernate.dialect.MySQLDialect
# Property that determines which JPA DatabasePlatform to use with TopLink Essentials
#jpa.databasePlatform=oracle.toplink.essentials.platform.database.MySQL4Platform
# Property that determines which database to use with an AbstractJpaVendorAdapter
解读jdbc.properties
<?xml version="1.0" encoding="UTF-8"?>
<!-- - DispatcherServlet application context for PetClinic's web tier. -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.2.xsd">
<!-- c3p0 的数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="minPoolSize" value="${c3p0.minPoolSize}"/>
<property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
<property name="initialPoolSize" value="${c3p0.initialPoolSize}"/>
<property name="maxIdleTime" value="${c3p0.maxIdleTime}"/>
<property name="acquireIncrement" value="${c3p0.acquireIncrement}"/>
<property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
<property name="acquireRetryDelay" value="${c3p0.acquireRetryDelay}"/>
<property name="testConnectionOnCheckin" value="${c3p0.testConnectionOnCheckin}"/>
<!-- <property name="automaticTestTable" value="${c3p0.automaticTestTable}"/> -->
<property name="idleConnectionTestPeriod" value="${c3p0.idleConnectionTestPeriod}"/>
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
</bean>
<context:property-placeholder
location="classpath:/conf/jdbc.properties" ignore-unresolvable="true" />
</beans>
说明
为了方便使用同样可以定义一个父类来初始化jdbcTemplate模板。
public abstract class AbstractDao {
protected DataSource dataSource;
protected JdbcTemplate jdbcTemplate;
public DataSource getDataSource() {
return this.dataSource;
}
@Autowired
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate=new JdbcTemplate(dataSource);
}
}
CURD操作
这里面主要讲一下返回对象时的做法,其余的CURD不具体讲解了,大家肯定都知道了。
所以直接拿代码来看区别吧。
传统的jdbc返回对象、List<Vo>的形式
/**
* 获取xx
* @param status
* @return List<UserTypeVO>
*/
public List<UserTypeVO> getUtypeList(int status){
String sql;
MapSqlParameterSource paramSource = new MapSqlParameterSource();
if(status==-1){
sql = "select * from type order by display_order asc";
}else{
sql = "select * from type where status=:status order by display_order asc";
paramSource.addValue("status",status);}
try {
SqlRowSet ret = this.namedJdbcTemplate.queryForRowSet(sql,paramSource);
List<UserTypeVO> list = new ArrayList<UserTypeVO>();
while (ret.next()) {
UserTypeVO utype_vo=new UserTypeVO();
utype_vo.setId(ret.getInt("id"));
utype_vo.setDisplay_order(ret.getInt("display_order"));
utype_vo.setUtype(ret.getInt("utype"));
utype_vo.setUtype_name(ret.getString("utype_name"));
utype_vo.setIf_change(ret.getInt("if_change"));
utype_vo.setStatus(ret.getInt("status"));
list.add(utype_vo);
}
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
说明
这个是很早jdbc使用方法,我们可以看出,使用queryForRowSet将数据查出之后,判断是否一直有值,有的话就一个个将值按id取出,set到对应的字段之中。
假设,我有100个字段,那么是不是要写100遍这样的代码?
所以,现在下面的这种方式,帮你做了回答,我们完全可以不管这些,只管SQL就行了。
自动组装对象、List<V0>示例
public class Dao extends AbstractDao{
private BeanPropertyRowMapper<UserVo> recRowMapper = new BeanPropertyRowMapper<UserVo>(UserVo.class)
/**
* 获取xx信息
*/
@Override
public List<UserVo> getUserVos(int status){
List<UserVo> UserVos = new ArrayList<UserVo>();
try {
String sql = "SELECT r.id, r.uid, r.display_order, r.status, r.create_time, r.update_time "
+ " FROM "
+ AppConstant.DATABASE_SCHEMA_APP_BB_APP
+ "." + AppConstant.DATABASE_TABLE_USER
+ " r WHERE r.status =:status AND u.uid = r.uid order by r.display_order asc ";
MapSqlParameterSource paramSource = new MapSqlParameterSource();
paramSource.addValue("status", status);
recommendUserVos = this.namedJdbcTemplate.query(sql, paramSource, recRowMapper);
} catch (Exception e) {
log.debug("there is an error on getDaoImpl sql or param please check in." + e);
}
return UserVos;
}
}
说明
两端代码对比得出、同样的返回List<Vo>的类型,下面代码就没有长长的组装对象的语句。为什么呢?
答案就是:1.它使用了
private BeanPropertyRowMapper<UserVo> recRowMapper = new BeanPropertyRowMapper<UserVo>(UserVo.class);这样一个方法,来自动装配对象。
那么它根据什么知道如何装配的呢?首先我们知道UserVo这里有哪些属性,同时我们结合了jdbc中this.namedJdbcTemplate.query(sql, paramSource, recRowMapper);这个方法,看方法中有一个参数为recRowMapper。由此得知是它们起了作用,在模板的帮助下,将其自动转换。
注意因为在自动装配的时候,一定要通过一个关键字才能拿到对应的值,那么如何知道那个关键字就是数据库中的呢?所以这时我们就需要将bean中的属性名字,和数据库中字段的名字完全一致,确保取到唯一准确值,这样才能对应封装为正确的Vo,或者List<Vo>,否则会报错的哦~
结束语:
这次总结,只总结了这个小用法,至于内部具体是如何实现的,喜欢的人可以自己看看源代码。
分享到:
相关推荐
JDBC类图、常用的JDBC类与方法~!~!
使用 Spring MVC + JDBC Template 实现筛选、检索功能(maven),图文教程地址:https://blog.csdn.net/qq_40147863/article/details/86187642
jdbc 和template结合的学生信息管理系统,包括增删改查
jdbc常用类方法和jsp白皮书
jdbc总结jdbc总结 jdbc总结 jdbc总结 jdbc总结
包括了jdbc的增删改查的方法,其中包含查询返回包括实体和Map结果,支持更新对象和保存对象的操作。
使用spring jdbc template简化jdbc数据库操作实例代码,简化操作,包括详细测试例子。
这是一个SpringMvc, JDBC Template的例子,希望对你有用
各种数据库的连接文档JDBC连接数据库经验总结
JDBC模板 仿Spring JDBC Template
在使用Spring框架处理mysql时用到的jar包
各种数据库JDBC连接方法总结-包括: SQL Server2000 、 SQL Server2005、Oracle、Access直连方法:(不写数据源名的桥连方法)、MySql、IBM DB2、Sybase、Informix、PostgreSQL、MaxDB、FrontBase、JavaDB/Derby等
Java应用程序访问数据库的基本原理 在Java语言中,JDBC(Java ...JDBC提供两种API,分别是面向开发人员的API和面向底层的JDBC驱动程序API,底层主要通过直接的JDBC驱动和JDBC-ODBC桥驱动实现与数据库的连接。
spring jdbc Templatetest 访问mysql数据库,批量插入数据
JDBC常用连接串JDBC常用连接串
看前面的那一版注释,加了同步,线程安全,封装了jdbc常用操作,增删改查,查询ResultSet指定位置的记录,返回ResultSet每个列的名字,查询ResultSet中记录的行数...... 含源代码,测试代码!!!! 另附API说明,powerdesign图,...
Java基础:常用的JDBC连接数据库方法大全Java基础:常用的JDBC连接数据库方法大全
主要介绍了JDBC常用接口总结,以及部分使用代码语句,需要的朋友可以参考下。
使用 Spring JDBC Template 对数据库查询(登录)和删除(maven),图文教程地址:https://blog.csdn.net/qq_40147863/article/details/86015509
在上一篇文章我们讲了一些基本使用JDBC-DBCP-MYBATIS。 1.防止SQL注入 我们在写sql语句时,为了方便可能会进行拼接字符串,这样做的弊端就是可能被sql注入攻击,解决的办法也很简单。 //获取数据库连接 Connection ...