Spring提供的JdbcTemplate对象

从Spring容器获取JdbcTemplate对象

Spring为我们提供了一个JdbcDaoSupport类,我们的dao实现类可以通过继承来获取JdbcTemplate.
使用步骤:
        1. dao中的实现类继承JdbcDaoSupport
        2. 通过getJdbcTemplate()或者加上this/super来直接获取一个JdbcTemplate对象来使用

使用需求:为其注入一个DataSource
        1. xml形式:
                1. dao中的实现类继承JdbcDaoSupport
                2. 配置xml文件
                    <!-- dao --> 给dao 注入一个datasource
                    <bean id="accountDao" class="cn.itheima.dao.AccountDAOImpl">
                        <!-- 当注入dataSource后,底层会自动创建一个JdbcTemplate -->
                        <property name="dataSource" ref="c3p0DataSource" />
                    </bean>
        2. 注解形式:
                @Repository("accountDao")
                public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
                    // 第一种:  为dao注入dataSource. 较常用
                    @Autowired
                    @Qualifier("dataSource")
                    public void setSuperDataSource(DataSource dataSource) {
                        super.setDataSource(dataSource);
                    }

                    // 第二种: 为dao注入
                      @Autowired
                    private JdbcTemplate jdbcTemplate;

                }
                本质: 就是能 拿到jdbcTemplate.执行sql语句

猜你喜欢

转载自blog.csdn.net/qq_35472880/article/details/83475226
今日推荐