JdbcTemplate

JdbcTemplate是最基本的Spring JDBC模板,这个模板支持简单的JDBC数据库访问功能以及基于索引参数的查询。

为了使 JDBC 更加易于使用,Spring 在 JDBCAPI 上定义了一个抽象层, 以此建立一个JDBC存取框架,Spring Boot Spring Data-JPA。

作为 SpringJDBC 框架的核心, JDBC 模板的设计目的是为不同类型的JDBC操作提供模板方法. 每个模板方法都能控制整个过程,并允许覆盖过程中的特定任务。

通过这种方式,可以在尽可能保留灵活性的情况下,将数据库存取的工作量降到最低。

 Spring JDBC由4个部分组成,即core、datasource、object、support。

  (1)core包:提供JDBC模板类,其中JdbcTemplate是core包的核心类。

  (2)datesource包:提供简化访问JDBC数据源工具类,并提供一些DataSource简单实现类,从而使这些DataSource获取的连接能自动得到Spring事务管理的支持。

  (3)object包:提供关系数据的对象表示形式,如MappingSqlQuery、SqlUpdate、SqlCall、SqlFunction等。

  (4)support包:提供将JDBC异常转换为DAO非检查异常的转化类和一些工具类。

JdbcTemplate主要提供以下五类方法:

execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;

update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate方法用于执行批处理相关语句;

query方法及queryForXXX方法:用于执行查询相关语句;

call方法:用于执行存储过程、函数相关语句。

JdbcTemplate实例(配置)

  实体类:

package com.te.entity;

public class Accounts {
    private int accountid;
    private String accountname;
    private double balance;

    public int getAccountid() {
        return accountid;
    }

    public void setAccountid(int accountid) {
        this.accountid = accountid;
    }

    public String getAccountname() {
        return accountname;
    }

    public void setAccountname(String accountname) {
        this.accountname = accountname;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }
}

  Dao接口层:

public interface AccountDao {
    //查询全部
    List<Accounts> getAll();
}

  Dao接口实现层:

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
    @Override
    public List<Accounts> getAll() {
        //RowMapper接口或抽象类
       /* List<Accounts> query = this.getJdbcTemplate().query("select * from accounts", new RowMapper<Accounts>() {
            public Accounts mapRow(ResultSet var1, int var2) throws SQLException {
                Accounts accounts=new Accounts();
                accounts.setAccountname(var1.getString("accountname"));
                accounts.setAccountid(var1.getInt("accountid"));
                accounts.setBalance(var1.getDouble("balance"));
                return accounts;
            }
        });*/
        List<Accounts> query = this.getJdbcTemplate().query("select * from accounts", new BeanPropertyRowMapper<>(Accounts.class));
        return query;
    }
}

  Service业务接口层:

public interface AccountService {
    //查询全部
    List<Accounts> getAll();
}

  ServiceImpl业务实现层:

public class AccountServiceImpl implements AccountService {

    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public List<Accounts> getAll() {
        return accountDao.getAll();
    }
}

  jdbc.properties 

driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///account
user=root
password=123

  applicationContext.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--添加jdbc-->
    <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties"></property>
    </bean>

    <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="url" value="${url}"></property>
        <property name="driverClassName" value="${driver}"></property>
        <property name="username" value="${user}"></property>
        <property name="password" value="${password}"></property>
    </bean>

    <!--配置jdbcTemplate核心对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--Dao接口的实现类对象-->
    <bean id="accountDao" class="com.te.daoimpl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>

    <!--service接口的实现类对象-->
    <bean id="accountService" class="com.te.serviceImpl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置事务-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="getAll" propagation="REQUIRED" isolation="READ_COMMITTED" />
        </tx:attributes>
    </tx:advice>
    <!--定义切面-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.te.service.*.*(..))"></aop:advisor>
    </aop:config>

</beans>

  测试:  

public class AccountTest {
    /*jdbcTemplate+Spring的整合*/
     @Test
    public void test01(){
         ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
         AccountService accountService = ctx.getBean("accountService",AccountService.class);
         for (Accounts accounts:accountService.getAll()){
             System.out.println("用户:"+accounts.getAccountname()+"====="+accounts.getBalance());
         }
     }
}

  结果:

    

JdbcTemplate实例(注解)

  entity实体类: 

package com.te.entity;

public class Accounts {
    private int accountid;
    private String accountname;
    private double balance;

    public int getAccountid() {
        return accountid;
    }

    public void setAccountid(int accountid) {
        this.accountid = accountid;
    }

    public String getAccountname() {
        return accountname;
    }

    public void setAccountname(String accountname) {
        this.accountname = accountname;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }
}

  Dao接口层:

public interface AccountDao {
    //查询全部
    List<Accounts> getAll();

}

  DaoImpl实现层:

@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Accounts> getAll() {
        //RowMapper接口或抽象类
       /* List<Accounts> query = this.getJdbcTemplate().query("select * from accounts", new RowMapper<Accounts>() {
            public Accounts mapRow(ResultSet var1, int var2) throws SQLException {
                Accounts accounts=new Accounts();
                accounts.setAccountname(var1.getString("accountname"));
                accounts.setAccountid(var1.getInt("accountid"));
                accounts.setBalance(var1.getDouble("balance"));
                return accounts;
            }
        });*/
        List<Accounts> query = this.jdbcTemplate.query("select * from accounts", new BeanPropertyRowMapper<>(Accounts.class));
        return query;
    }
}

  Service业务层:

public interface AccountService {
    //查询全部
    List<Accounts> getAll();
}

  ServiceImpl业务实现层:

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Resource(name = "accountDao")
    private AccountDao accountDao;

    @Override
    public List<Accounts> getAll() {
        return accountDao.getAll();
    }
}

  applicationContext.xml文件:

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

    <!--扫描注解-->
    <context:component-scan base-package="com.zhu"></context:component-scan>

    <!--添加jdbc-->
    <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties"></property>
    </bean>

    <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="url" value="${url}"></property>
        <property name="driverClassName" value="${driver}"></property>
        <property name="username" value="${user}"></property>
        <property name="password" value="${password}"></property>
    </bean>

    <!--配置jdbcTemplate核心对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>


</beans>

  测试:

public class ZhuTeset {
         @Test
        public void test01(){
            ApplicationContext ctx=new ClassPathXmlApplicationContext("application-zhu.xml");
            AccountService accountServiceImpl = (AccountService) ctx.getBean("accountService");
            List<Accounts> all = accountServiceImpl.getAll();
            for (Accounts accounts:all){
                System.out.println(accounts.getAccountname());
            }
        }
}

  结果:

    

原文地址:https://www.cnblogs.com/wnwn/p/11783453.html