Spring模板类

发布于 2020-04-02  110 热度


概述

Spring提供了很多持久层技术的模板类简化编程:

ORM持久化技术 模板类
JDBC org.springframework.jdbc.core.JdbcTemplate
Hibernate3.0 org.springframework.orm.hibernate3.HibernateTemplate
Ibatis(Mybatis) org.springframework.orm.ibatis.SqlMapClientTemplate
JPA org.springframework.orm.jpa.JpaTemplate

在此讲解Spring的JDBC模板对象,其余应该同理。

JDBC模板对象

Spring中提供了一个可以操作数据库的对象.对象封装了jdbc技术.
JDBCTemplate就是JDBC模板对象,与DBUtils中的QueryRunner非常相似.
如:

ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql:///hibernate_32");
dataSource.setUser("root");
dataSource.setPassword("1234");
//1 创建JDBC模板对象
JdbcTemplate jt = new JdbcTemplate();
jt.setDataSource(dataSource);
//2 书写sql,并执行
String sql = "insert into t_user values(null,'rose') ";
jt.update(sql);

步骤

导包

4个Spring核心包、2个apache日志包、spring-test、spring-aop
、junit4类库、c3p0连接池、JDBC驱动、spring-jdbc、spring-tx

准备数据库

t_user:

列名 数据类型
id int
name varchar

书写代码

User.java

package cn.itcast.bean;

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 + "]";
    }
}

UserDao.java

package cn.itcast.a_jdbctemplate;

import java.util.List;

import cn.itcast.bean.User;

public interface UserDao {

    //增
    void save(User u);
    //删
    void delete(Integer id);
    //改
    void update(User u);
    //查
    User getById(Integer id);
    //查
    int getTotalCount();
    //查
    List<User> getAll();
}

UserDaoImpl.java

package cn.itcast.a_jdbctemplate;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import cn.itcast.bean.User;
//使用JDBC模板实现增删改查
public class UserDaoImpl extends JdbcDaoSupport implements UserDao {
    @Override
    public void save(User u) {
        String sql = "insert into t_user values(null,?) ";
        super.getJdbcTemplate().update(sql, u.getName());
    }
    @Override
    public void delete(Integer id) {
        String sql = "delete from t_user where id = ? ";
        super.getJdbcTemplate().update(sql,id);
    }
    @Override
    public void update(User u) {
        String sql = "update  t_user set name = ? where id=? ";
        super.getJdbcTemplate().update(sql, u.getName(),u.getId());
    }
    @Override
    public User getById(Integer id) {
        String sql = "select * from t_user where id = ? ";
        return super.getJdbcTemplate().queryForObject(sql,new RowMapper<User>(){
            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }}, id);
    }
    @Override
    public int getTotalCount() {
        String sql = "select count(*) from t_user  ";
        Integer count = super.getJdbcTemplate().queryForObject(sql, Integer.class);
        return count;
    }

    @Override
    public List<User> getAll() {
        String sql = "select * from t_user  ";
        List<User> list = super.getJdbcTemplate().query(sql, new RowMapper<User>(){
            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }});
        return list;
    }
}

书写配置

db.properties

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

applicationContext.xml

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

    <!-- 指定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="cn.itcast.a_jdbctemplate.UserDaoImpl" >
        <!--
            如果DaoImpl中不继承JdbcDaoSupport
            也可以使用一个成员变量private JdbcTemplate jt来实现
            这就需要把jdbcTemplate注入jt(也可以使用注释注入)
            <property name="jt" ref="jdbcTemplate" ></property>
        -->
        <property name="dataSource" ref="dataSource" ></property>
    </bean>
</beans>

书写测试代码

Demo.java

package cn.itcast.a_jdbctemplate;

import java.beans.PropertyVetoException;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import cn.itcast.bean.User;

@RunWith(SpringJUnit4ClassRunner.class)//使用JUnit4测试
@ContextConfiguration("classpath:applicationContext.xml")//引入Spring核心配置
public class Demo {
    @Resource(name="userDao")//注入userDao
    private UserDao ud;
    @Test
    public void fun2() throws Exception{
        User u = new User();
        u.setName("tom");
        ud.save(u);
    }
    @Test
    public void fun3() throws Exception{
        User u = new User();
        u.setId(2);
        u.setName("jack");
        ud.update(u);

    }

    @Test
    public void fun4() throws Exception{
        ud.delete(2);
    }

    @Test
    public void fun5() throws Exception{
        System.out.println(ud.getTotalCount());
    }

    @Test
    public void fun6() throws Exception{
        System.out.println(ud.getById(1));
    }

    @Test
    public void fun7() throws Exception{
        System.out.println(ud.getAll());
    }
}

我一直在开辟我的天空