Spring入门详细教程四

前言

本篇紧接着spring入门详细教程(三),建议阅读本篇前,先阅读第一篇,第二篇以及第三篇。链接如下:

Spring入门详细教程(一) https://www.cnblogs.com/jichi/p/10165538.html

Spring入门详细教程(二) https://www.cnblogs.com/jichi/p/10176601.html

Spring入门详细教程(三) https://www.cnblogs.com/jichi/p/10177004.html

本篇主要讲解spring的jdbcTemplate相关。

一、spring整合jdbc继承jdbcdaosupport的方式

1、导入所需jar包。

除了之前介绍的spring的基础包,还需要导入数据库连接池包,jdbc驱动包,spring的jdbc包,spring的事务。

2、书写dao层代码。

public class UserDaoImpl extends JdbcDaoSupport implements UserDao {
    @Override
    void save(User u) {
        String sql = "insert into user values('1',?) ";
        super.getJdbcTemplate().update(sql,u.getName());
    }
    @Override
     delete(Integer id) {
        String sql = "delete from user where id = ? " update(User u) {
        String sql = "update  user set name = ? where id=? "public User getById(Integer id) {
        String sql = "select * from user where id = ? "return super.getJdbcTemplate().queryForObject(sql,new RowMapper<User>(){
            @Override
            public User mapRow(ResultSet rs,1)">int arg1) throws SQLException {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }},id);
        
    }
    @Override
    int getTotalCount() {
        String sql = "select count(*) from user  ";
        Integer count = class);
         count;
    }
    @Override
    public List<User> getAll() {
        String sql = "select * from user  ";
        List<User> list = super.getJdbcTemplate().query(sql,1)"> u;
            }});
         list;
    }
}

3、建立数据库链接配置文件

jdbc.jdbcUrl=jdbc:mysql:///spring
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=1234

4、在spring容器中进行配置

<!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties"  />
<!-- 将连接池放入spring容器 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
    <property name="driverClass" value="${jdbc.driverClass}" ></property>
    <property name="user" value="${jdbc.user}" ></property>
    <property name="password" value="${jdbc.password}" ></property>
</bean>
<!-- 将UserDao放入spring容器 -->
<bean name="userDao" class="com.jichi.jdbctemplate.UserDaoImpl" >
    <property name="dataSource" ref="dataSource" ></property>
</bean>

5、由于userDaoImpl已经继承了jdbcDaoSupport。jdbcDaoSupport中已经定义了jdbcTemplate,同时内置了setDataSource。可以自动将连接池放入。源码如下:

/*
 * Copyright 2002-2012 the original author or authors.
 *
 * Licensed under the Apache License,Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,software
 * distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.jdbc.core.support;

import java.sql.Connection;
 javax.sql.DataSource;

 org.springframework.dao.support.DaoSupport;
 org.springframework.jdbc.CannotGetJdbcConnectionException;
 org.springframework.jdbc.core.JdbcTemplate;
 org.springframework.jdbc.datasource.DataSourceUtils;
 org.springframework.jdbc.support.SQLExceptionTranslator;

/**
 * Convenient super class for JDBC-based data access objects.
 *
 * <p>Requires a {@link javax.sql.DataSource} to be set,providing a
 * { org.springframework.jdbc.core.JdbcTemplate} based on it to
 * subclasses through the { #getJdbcTemplate()} method.
 *
 * <p>This base class is mainly intended for JdbcTemplate usage but can
 * also be used when working with a Connection directly or when using
 * {@code org.springframework.jdbc.object} operation objects.
 *
 * @author Juergen Hoeller
 * @since 28.07.2003
 * @see #setDataSource
 *  #getJdbcTemplate
 *  org.springframework.jdbc.core.JdbcTemplate
 */
abstract class JdbcDaoSupport extends DaoSupport {

    private JdbcTemplate jdbcTemplate;


    
     * Set the JDBC DataSource to be used by this DAO.
     */
    final  setDataSource(DataSource dataSource) {
        if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) {
            this.jdbcTemplate = createJdbcTemplate(dataSource);
            initTemplateConfig();
        }
    }

    
     * Create a JdbcTemplate for the given DataSource.
     * Only invoked if populating the DAO with a DataSource reference!
     * <p>Can be overridden in subclasses to provide a JdbcTemplate instance
     * with different configuration,or a custom JdbcTemplate subclass.
     * @param dataSource the JDBC DataSource to create a JdbcTemplate for
     * @return the new JdbcTemplate instance
     *  #setDataSource
     protected JdbcTemplate createJdbcTemplate(DataSource dataSource) {
         JdbcTemplate(dataSource);
    }

    
     * Return the JDBC DataSource used by this DAO.
     final DataSource getDataSource() {
        return (this.jdbcTemplate != null ? this.jdbcTemplate.getDataSource() : null);
    }

    
     * Set the JdbcTemplate for this DAO explicitly,* as an alternative to specifying a DataSource.
      setJdbcTemplate(JdbcTemplate jdbcTemplate) {
         jdbcTemplate;
        initTemplateConfig();
    }

    
     * Return the JdbcTemplate for this DAO,* pre-initialized with the DataSource or set explicitly.
      JdbcTemplate getJdbcTemplate() {
      .jdbcTemplate;
    }

    
     * Initialize the template-based configuration of this DAO.
     * Called after a new JdbcTemplate has been set,either directly
     * or through a DataSource.
     * <p>This implementation is empty. Subclasses may override this
     * to configure further objects based on the JdbcTemplate.
     *  #getJdbcTemplate()
     protected  initTemplateConfig() {
    }

    @Override
     checkDaoConfig() {
        ) {
            throw new IllegalArgumentException("'dataSource' or 'jdbcTemplate' is required");
        }
    }


    
     * Return the SQLExceptionTranslator of this DAO's JdbcTemplate,* for translating SQLExceptions in custom JDBC access code.
     *  org.springframework.jdbc.core.JdbcTemplate#getExceptionTranslator()
      SQLExceptionTranslator getExceptionTranslator() {
         getJdbcTemplate().getExceptionTranslator();
    }

    
     * Get a JDBC Connection,either from the current transaction or a new one.
     *  the JDBC Connection
     * @throws CannotGetJdbcConnectionException if the attempt to get a Connection failed
     *  org.springframework.jdbc.datasource.DataSourceUtils#getConnection(javax.sql.DataSource)
     final Connection getConnection()  CannotGetJdbcConnectionException {
         DataSourceUtils.getConnection(getDataSource());
    }

    
     * Close the given JDBC Connection,created via this DAO's DataSource,* if it isn't bound to the thread.
     *  con Connection to close
     *  org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection
      releaseConnection(Connection con) {
        DataSourceUtils.releaseConnection(con,getDataSource());
    }

}

6、编写测试类

    @Test
    void fun2()  Exception{
        User u =  User();
        u.setName("tom");
        ud.save(u);
    }

7、执行成功

二、spring整合jdbctemplate

1、导入所需jar包。

除了之前介绍的spring的基础包,还需要导入数据库连接池包,jdbc驱动包,spring的jdbc包,spring的事务。

2、配置jdbctemplate

<!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties"  />
<!-- 1.将连接池放入spring容器 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
    <property name="driverClass" value="${jdbc.driverClass}" ></property>
    <property name="user" value="${jdbc.user}" ></property>
    <property name="password" value="${jdbc.password}" ></property>
</bean>
<!-- 2.将JDBCTemplate放入spring容器 -->
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
    <property name="dataSource" ref="dataSource" ></property>
</bean>
<!-- 3.将UserDao放入spring容器 -->
<bean name="userDao" class="com.jichi.jdbctemplate.UserDaoImpl" >
    <property name="jdbcTemplate" ref="jdbcTemplate" ></property>
</bean>

3、书写dao层代码

class UserDaoImpl   UserDao {
    
    @Resource
     JdbcTemplate jdbcTemplate;
    
    @Override
    ;
        jdbcTemplate.update(sql,1)">return jdbcTemplate.queryForObject(sql,1)">;
        Integer count = jdbcTemplate.queryForObject(sql,1)">;
        List<User> list = jdbcTemplate.query(sql,1)"> list;
    }
}

4、书写测试方法

);
        ud.save(u);
    }

三、spring中jdbctemplate的相关方法

1、update

用来执行insert,update,delete语句。

    @Override
    
 count;
    }

3、将查询的数据封入实体类(单个对象,实现rowmapper接口)


 list;
    }

5、根据数据库查出的字段与实体类字段名自动对应

new BeanPropertyRowMapper<>(User.));
         list;
    }

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原理介绍,具有一定借鉴价值,需要的朋友可以参考下。下面就和我一起来看看吧。传统事务中回滚点的使...
今天小编给大家分享的是一文解析spring中事务的传播机制,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧。一定会有所收获...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区别,具有一定借鉴价值,需要的朋友可以参考下。下面就和我一起来看看吧。Spring Cloud Netfli...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。第一步:整合pom文件,在S...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。List 坑列表 = new ArrayList(2);...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓存的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇...
本篇内容主要讲解“Spring中的@Autowired和@Resource注解怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学...
今天小编给大家分享一下SpringSecurity怎么定义多个过滤器链的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家
这篇文章主要介绍“Spring的@Conditional注解怎么使用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Spring的@Con...
这篇文章主要介绍了SpringCloudGateway的熔断限流怎么配置的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇SpringCloud&nb...
今天小编给大家分享一下怎么使用Spring解决循环依赖问题的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考
这篇文章主要介绍“Spring事务及传播机制的原理及应用方法是什么”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Sp...
这篇“SpringCloudAlibaba框架实例应用分析”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价
本篇内容主要讲解“SpringBoot中怎么使用SpringMVC”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习...
这篇文章主要介绍“SpringMVC适配器模式作用范围是什么”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“SpringMVC
这篇“导入SpringCloud依赖失败如何解决”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家...
这篇文章主要讲解了“SpringMVC核心DispatcherServlet处理流程是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来
今天小编给大家分享一下SpringMVCHttpMessageConverter消息转换器怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以...
这篇文章主要介绍“Spring框架实现依赖注入的原理是什么”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Spring框架...
本篇内容介绍了“Spring单元测试控制Bean注入的方法是什么”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下