JDBC template常用方法总结

[b][size=medium][size=xx-small]前言[/size][/size][/b]

本来对用法不是很想总结的,因为这些东西都是拿过来用,对原理不理解的我,觉得写这些总结就和网上铺天盖地的文章一样。但是昨天写了一篇发现想用的话其中还是有那么点问题的。所以就把JDBC template的常用总结再写一遍吧。

好啦,言归正传。
[b][size=medium]
JDBC 配置
[/size][/b]


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>


[b][size=medium]说明[/size][/b]
为了方便使用同样可以定义一个父类来初始化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);
}
}


[b][size=medium]CURD操作[/size][/b]

这里面主要讲一下返回对象时的做法,其余的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;
}


[b][size=medium]说明[/size][/b]

这个是很早jdbc使用方法,我们可以看出,使用queryForRowSet将数据查出之后,判断是否一直有值,有的话就一个个将值按id取出,set到对应的字段之中。

假设,我有100个字段,那么是不是要写100遍这样的代码?

所以,现在下面的这种方式,帮你做了回答,我们完全可以不管这些,只管SQL就行了。

[b][size=medium]自动组装对象、List<V0>示例[/size][/b]


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;
}
}


[b][size=medium]说明[/size][/b]

两端代码对比得出、同样的返回List<Vo>的类型,下面代码就没有长长的组装对象的语句。为什么呢?

答案就是:1.它使用了[b]private BeanPropertyRowMapper<UserVo> recRowMapper = new BeanPropertyRowMapper<UserVo>(UserVo.class);[/b]这样一个方法,来自动装配对象。

那么它根据什么知道如何装配的呢?首先我们知道UserVo这里有哪些属性,同时我们结合了jdbc中this.namedJdbcTemplate.query(sql, paramSource, recRowMapper);这个方法,看方法中有一个参数为recRowMapper。由此得知是它们起了作用,在模板的帮助下,将其自动转换。

[b] 注意[/b]因为在自动装配的时候,一定要通过一个关键字才能拿到对应的值,那么如何知道那个关键字就是数据库中的呢?所以这时我们就需要将bean中的属性名字,和数据库中字段的名字完全一致,确保取到唯一准确值,这样才能对应封装为正确的Vo,或者List<Vo>,否则会报错的哦~

[b][size=medium]结束语:
[/size][/b]
这次总结,只总结了这个小用法,至于内部具体是如何实现的,喜欢的人可以自己看看源代码。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值