Spring学习-26:Spring中的JDBC Template(JDBC模板):完成增删改的操作

    xiaoxiao2021-04-13  33

    现在开始,介绍一下使用JDBC模板来实现增删改查的操作。

    首先给大家介绍,增删改的操作。

    1、定义实体类:

    package com.js.demo2; public class User { private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User [id=" + id + ", name=" + name + "]"; } }

    2、定义Dao:

    由于Spring框架中提供了对持久层技术支持的类:

    JDBC         :   org.springframework.jdbc.core.support.JdbcDaoSupport

    Hibernate 3.0    :   org.springframework.orm.hibernate3.support.HibernateDaoSupport

    iBatis       :   org.springframework.orm.ibatis.support.SqlMapClientDaoSupport

    所以,在编写DAO的时候,我们继承JdbcDaoSupport类,可以获得其实现的取得jdbc template的方法。

    参看JdbcDaoSupport类源码:

    /* * Copyright 2002-2008 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; import javax.sql.DataSource; import org.springframework.dao.support.DaoSupport; import org.springframework.jdbc.CannotGetJdbcConnectionException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceUtils; import 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 * {@link org.springframework.jdbc.core.JdbcTemplate} based on it to * subclasses through the {@link #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</code> operation objects. * * @author Juergen Hoeller * @since 28.07.2003 * @see #setDataSource * @see #getJdbcTemplate * @see org.springframework.jdbc.core.JdbcTemplate */ public abstract class JdbcDaoSupport extends DaoSupport { private JdbcTemplate jdbcTemplate; /** * Set the JDBC DataSource to be used by this DAO. */ public final void 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 * @see #setDataSource */ protected JdbcTemplate createJdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); } /** * Return the JDBC DataSource used by this DAO. */ public 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. */ public final void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; initTemplateConfig(); } /** * Return the JdbcTemplate for this DAO, * pre-initialized with the DataSource or set explicitly. */ public final JdbcTemplate getJdbcTemplate() { return this.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. * @see #getJdbcTemplate() */ protected void initTemplateConfig() { } @Override protected void checkDaoConfig() { if (this.jdbcTemplate == null) { throw new IllegalArgumentException("'dataSource' or 'jdbcTemplate' is required"); } } /** * Return the SQLExceptionTranslator of this DAO's JdbcTemplate, * for translating SQLExceptions in custom JDBC access code. * @see org.springframework.jdbc.core.JdbcTemplate#getExceptionTranslator() */ protected final SQLExceptionTranslator getExceptionTranslator() { return getJdbcTemplate().getExceptionTranslator(); } /** * Get a JDBC Connection, either from the current transaction or a new one. * @return the JDBC Connection * @throws CannotGetJdbcConnectionException if the attempt to get a Connection failed * @see org.springframework.jdbc.datasource.DataSourceUtils#getConnection(javax.sql.DataSource) */ protected final Connection getConnection() throws CannotGetJdbcConnectionException { return DataSourceUtils.getConnection(getDataSource()); } /** * Close the given JDBC Connection, created via this DAO's DataSource, * if it isn't bound to the thread. * @param con Connection to close * @see org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection */ protected final void releaseConnection(Connection con) { DataSourceUtils.releaseConnection(con, getDataSource()); } } 所以,我们编写的UserDao如下所示 进行增删改查(CRUD)操作,它们调用的都是update(String sql,Object...args)方法

    package com.js.demo2; import org.springframework.jdbc.core.support.JdbcDaoSupport; public class UserDao extends JdbcDaoSupport{ public void add(User user){ String sql="insert into user values (null,?)"; this.getJdbcTemplate().update(sql, user.getName()); } public void delete(User user){ String sql="update user set name=? where id=?"; this.getJdbcTemplate().update(sql, user.getName(),user.getId()); } public void update(User user){ String sql="delete from user where id=?"; this.getJdbcTemplate().update(sql, user.getId()); } } 3、编写测试类,测试添加功能。 package com.js.demo2; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContextCRUD.xml") public class SpringTest { @Autowired @Qualifier("userDao") private UserDao userDao; @Test public void demo1(){ User user = new User(); user.setName("王二麻子"); userDao.add(user); } } 记录添加成功:

    测试修改功能:

    package com.js.demo2; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContextCRUD.xml") public class SpringTest { @Autowired @Qualifier("userDao") private UserDao userDao; @Test public void demo1(){ User user = new User(); user.setId(1); user.setName("小王"); userDao.update(user); } }

    记录修改成功:

    测试删除功能:

    package com.js.demo2; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContextCRUD.xml") public class SpringTest { @Autowired @Qualifier("userDao") private UserDao userDao; @Test public void demo1(){ User user = new User(); user.setId(1); userDao.delete(user); } }

    记录删除成功:

    这是我们的增删改的方法,而查询的操作相对于增删改的操作,要麻烦一些,我们下一讲专门介绍查询的操作。

    转载请注明原文地址: https://ju.6miu.com/read-669020.html

    最新回复(0)