springframework(十三)spring的Dao和JDBC

DAOData Access Object),我们开发的时候通常采用一接口一实现的方式。Dao所抛出的异常在spring中都是DataAccessException的子类,并且DataAccessExceptionRuntimeException,也就是说他属于unchecked Exception

1、  DataSource注入:对于不同的数据连接来源需求,spring提供了javax.sql.DataSource注入,要更换数据源只要在bean的定义文件中修改,不需要修改任何一行程序代码

写法如下:

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>

<property name="url" value="jdbc:mysql://localhost:3306/spring"></property>

<property name="username" value="root"></property>

<property name="password" value="spring_framework"></property>

</bean>

此处需要注意的是,一定要引入相关的数据库驱动jar包。并在配置文件中进行dao的数据源注入。

2、  置换DataSource数据源

置换数据源并不需要修改源代码程序,只需要更改下配置文件就ok了,同时记得相关jar包引入。这里我们想置换当前数据源连接策略为dbcp

引入的jar为:commons-dbcp.jar,commons-pool.jar

写法如下:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>

<property name="url" value="jdbc:mysql://localhost:3306/spring"></property>

<property name="username" value="root"></property>

<property name="password" value="spring_framework"></property>

</bean>

大家可以看到只是beanclass改变了!!

3、  jndi数据源的支持

 如果你要设置jndi数据源,请引入相关的jarspring-context.jar,同时在tomcat应用服务器上配置好jndi的数据源,在配置文件中引用

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">

<property name="jndiName" value="jdbc/demo"></property>

</bean>

 

4、  Springjdbc封装功能(Template

Spring提供的jdbc的封装等功能是可以独立于spring来使用,除了JdbcTemplate类之外,spring还提供了其他的Template类,例如:hibernatejdoibatis等的Template实现。这些都是线程安全的。

      1)、JdbcTemplate的使用

         我们将改写InsertUser方法,使用jdbcTemplate技术

         核心代码如下:

       JdbcTemplate tmp = new JdbcTemplate(dataSource);

       tmp.execute("insert  into tbl_user (name,pwd) values ('"+user.getName()+"','"+user.getPwd()+"')");

      2)、jdbcTemplate的查询

         通过调用queryForInt方法来进行个数查询

例如:  int total = tmp.queryForInt("select count(*) from tbl_user");

         通过调用queryForObject方法来对查询出的数据进行对象封装

例如:      User user = (User) tmp.queryForObject("select * from tbl_user where id="+id, new UserRowMapper());

         通过调用query方法来对查询出的列表数据进行对象封装

例如:      List<User> list= (List<User>) tmp.query("select * from tbl_user", new UserRowMapper());      

      进行查询出的数据进行对象封装的关键点是封装类的实现:实现RowMapper接口

        封装对象的写法如下:

    public class UserRowMapper implements RowMapper {

    public Object mapRow(ResultSet rs, int rowNum) throws SQLException {

       User user = new User();

       user.setId(new Integer(rs.getInt("id")));

       user.setName(rs.getString("name"));

       user.setPwd(rs.getString("pwd"));

       return user;

    }

}

5、  以对象的方式操作

JdbcTemplate上的各种方法来看,它封装了JDBC的处理细节,让您不需要接触底层的数据库技术,然而JdbcTemplate的各种方法仍然需要熟悉如何使用sql语法,如果想让程序人员不用接触到sql的于案发或者是重用某些sql,在spring中,可以进一步建立可重用的操作对象,建立之后在数据库设计时,将设计完成的可重用对象给开发人员使用,他们就无须接触到sql的细节了。

  Spring提供了org.springframework.jdbc.object包,只要继承它下边的已经提供的对象实例,就可以完成以对象为导向的数据库操作。这些类都被设计成线程安全的。

1)、继承sqlFunction

public class UserFunction extends SqlFunction {

 

  public UserFunction(DataSource dataSource){

     super(dataSource,"select count(*) from tbl_user");

     compile();

  }

 

}

     调用:

       UserFunction uf = new UserFunction(dataSource);

       total =uf.run();

      2)、继承sqlUpdate

public class UserUpdate extends SqlUpdate {

    public UserUpdate(DataSource dataSource){

       super(dataSource,"insert into tbl_user (name,pwd) values (?,?)");

       int[] types = {java.sql.Types.VARCHAR,java.sql.Types.VARCHAR};

       setTypes(types);

       compile();

      

    }

}

调用:

          UserUpdate uu = new UserUpdate(dataSource);

        uu.update(new Object[]{user.getName(),user.getPwd()});

3)、继承MappingSqlQuery

 public class UserQuery extends MappingSqlQuery {

    public UserQuery(DataSource dataSource){

       super(dataSource,"select * from tbl_user");

       compile();

    }

    @Override

    protected Object mapRow(ResultSet rs, int rowNum) throws SQLException {

       User user = new User();

       user.setId(new Integer(rs.getInt("id")));

       user.setName(rs.getString("name"));

       user.setPwd(rs.getString("pwd"));

       return user;

    }

}

调用:

        UserQuery uq = new UserQuery(dataSource);

        List<User> list=uq.execute();

6、  Spring2.0NamedParameterJdbcTemplate

在编写jdbcsql陈述时就不必使用占位符’?’了,而是使用实际的命名参数来保留sql中会变动的数据部分。

例如:

String sql = “select * from tbl_user where id =:userId”;

SqlParameterSource params = new MapSqlParameterSource(“userId”,id);

NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(dataSource);

List rows = template.queryForList(sql,params);

7、  Spring2.0SimpleJdbcTemplate

如果使用的是jdk1.5以上的版本,可以利用这个函数所提供的泛型的功能来查询数据。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值