spring中jdbc封装

Posted on 2004-08-26 16:10  数码民工  阅读(2962)  评论(0编辑  收藏  举报
spring中jdbc部分由4个包组成:core, datasource, object和support。
org.springframework.jdbc.core包主要提供核心功能,包含了sql异常转换和字段最大值增加等功能。
org.springframework.jdbc.datasource包提供一个易用的数据源存取方法,使得数据源代的测试和运行都变得非常容易。此外还提供从JNDI获取数据连接的静态方法以及DataSourceTransactionManager。
org.springframework.jdbc.object包含RDBMS查询、更新、存储过程等线程安全可重用的类。
org.springframework.jdbc.support包含sql异常转换过程以及其他支持工具类。

JDBCTemplate

这个是croe包中最主要的类。他负责了资源的创建和释放,从而避免一些常常会犯的错误,例如忘记关闭连接。该类封装了常用的jdbc操作,例如statement的创建和执行,提供sql语句,得到数据集等。该类还可以捕捉异常并且转换。
在程序中使用这个类只需要实现一些回调借口。PreparedStatementCreator回调接口可以创建一个prepared statement,提供连接、sql语句以及需要的参数。RowCallbackHandler接口可以实现从数据集中得到每一行的值。

DataSource

我们可以直接使用Spring JDBC中的数据源来获取一个数据连接。数据源可以在JNDI也可以在配置文件中。这样你离开web容器也可以进行单元测试。通过DriverManagerDataSource类的设置生成一个数据源。你需要设置驱动类名称,url,用户名和密码。例如:
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName( "org.hsqldb.jdbcDriver");
dataSource.setUrl( "jdbc:hsqldb:hsql://localhost:");
dataSource.setUsername( "sa");
dataSource.setPassword( "");

SQLExceptionTranslator

SQLExceptionTranslator该接口可以被实现以便来转换SQLExceptions和springframework.dao.DataAccessException层面的异常提示。
SQLErrorCodeSQLExceptionTranslator是SQLExceptionTranslator的一个实现。
可以使用自己定义的SQLErrorCodeSQLExceptionTranslator来显示异常(在sql-error-codes.xml中定义)。
public class MySQLErrorCodesTransalator extends SQLErrorCodeSQLExceptionTranslator {
protected DataAccessException customTranslate(String task, String sql, SQLException sqlex) {
if (sqlex.getErrorCode() == -12345)
return new DeadlockLoserDataAccessException(task, sqlex);
return null;
}
}
使用的例子:
// create a JdbcTemplate and set data source
JdbcTemplate jt = new JdbcTemplate();
jt.setDataSource(dataSource);
// create a custom translator and set the datasource for the default translation lookup
MySQLErrorCodesTransalator tr = new MySQLErrorCodesTransalator();
tr.setDataSource(dataSource);
jt.setExceptionTranslator(tr);
// use the JdbcTemplate for this SqlUpdate
SqlUpdate su = new SqlUpdate();
su.setJdbcTemplate(jt);
su.setSql("update orders set shipping_charge = shipping_charge * 1.05");
su.compile();
su.update();

Executing Statements

只需要很少的代码就可以执行SQL statement。你只需要使用一个数据源和一个jdbcTemplate。这样你可以使用jdbcTemplate提供的大量方法。创建一个数据表的例子:
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class ExecuteAStatement {
        private JdbcTemplate jt;
        private DataSource dataSource;
        public void doExecute() {
                jt = new JdbcTemplate(dataSource);
                jt.execute("create table mytable (id integer, name varchar(100))");
       }
       public void setDataSource(DataSource dataSource) {
               this.dataSource = dataSource;
      }
}

Running Queries(执行查询)

在jdbcTemplate中有很多产旬方法,通过这些方法可以得到各种类型的值。queryForInt,queryForLong ,queryForObject使用不同的方法返回不同的类型值。此外可以将查询的结果转换为java类。
下面是一个查询的例子,一个得到int值,一个得到string值。
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;

public class RunAQuery {
        private JdbcTemplate jt;
        private DataSource dataSource;
        public int getCount() {
                jt = new JdbcTemplate(dataSource);
                int count = jt.queryForInt("select count(*) from mytable");
                return count;
       }

       public String getName() {
                 jt = new JdbcTemplate(dataSource);
                 String name = (String) jt.queryForObject("select name from        mytable",  java.lang.String.class);
                 return name;
       }
        public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
       }
}

一些方法可以返回List,包含每个Row的数据。List中包含的每个Row的实体都是一个Map,Map由该行中每个列的列名和值组成。类似[{name=Bob, id=1}, {name=Mary, id=2}].这样。
使用QueryForList方法可以返回List
public List getList() {
         jt = new JdbcTemplate(dataSource);
         List rows = jt.queryForList("select * from mytable");
         return rows;
}

Updating the database(更新数据)

和查询一样,jdbcTemplate提供了一些简单的方法供我们使用。更新语句需要用到的参数使用数组来表示。
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class ExecuteAnUpdate {
         private JdbcTemplate jt;
         private DataSource dataSource;
         public void setName(int id, String name) {
                   jt = new JdbcTemplate(dataSource);
                   jt.update("update mytable set name = ? where id = ?", new Object[] {name, new Integer(id)});
         }
         public void setDataSource(DataSource dataSource) {
                   this.dataSource = dataSource;
        }
}

Copyright © 2024 数码民工
Powered by .NET 8.0 on Kubernetes