Spring之jdbc【继承JdbcDaoSupport】

dao层类UserDaoImpl继承JdbcDaoSupport并且取消该类上的注解,将之前temp对象改写成getJdbcTemplate(),其次在Spring的IOC容器中配置UserDaoImpl的bean,并把DataSource注入进来

全局配置文件beans.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    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/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:component-scan base-package="com" />

    <bean id="ds" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="root" />
        <property name="password" value="root" />
        <property name="jdbcUrl" value="jdbc:mysql:///db_test" />
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
    </bean>

    <bean id="dao" class="com.dao.UserDaoImpl">
        <property name="dataSource" ref="ds" />
    </bean>


</beans>

 

 

UserDaoImpl代码如下:

public class UserDaoImpl extends JdbcDaoSupport implements UserDao {

    @Override
    public boolean add(User user) {
        String sql = "insert into user values(?, ?, ?, ?)";
        int update = getJdbcTemplate().update(sql, user.getId(), user.getName(),
                user.getAge(), user.getAddress());
        return update > 0 ? true : false;
    }

    @Override
    public boolean update(User user) {
        String sql = "update user set name=?, age=?, address=? where id=?";
        int update = getJdbcTemplate().update(sql, user.getName(), user.getAge(),
                user.getAddress(), user.getId());
        return update > 0 ? true : false;
    }
}

 

posted @ 2017-10-03 11:01  JaneBaby  阅读(462)  评论(0编辑  收藏  举报