• spring框架学习笔记6:JDBC模板


    JDBC模板:Spring中对数据库的操作。

    这一部分对熟悉DBUtils的QueryRunner的开发者来说,非常简单

    这是以前我简单写的dbutils的知识:

    http://www.cnblogs.com/xuyiqing/p/8397428.html

    导包:

    1.spring中的包

    2.c3p0连接池包

    3.数据库驱动包

    最终导入这些包:

    2.准备数据库测试:

    简单的测试:

        @Test
        public void fun1() throws Exception{
            
            //准备连接池
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            dataSource.setDriverClass("com.mysql.jdbc.Driver");
            dataSource.setJdbcUrl("jdbc:mysql:///mybase");
            dataSource.setUser("root");
            dataSource.setPassword("xuyiqing");
            //1 创建JDBC模板对象
            JdbcTemplate jt = new JdbcTemplate();
            jt.setDataSource(dataSource);
            //2 书写sql,并执行
            String sql = "insert into t_user values(null,'Tom') ";
            jt.update(sql);
            
        }

    接下来使用Spring框架管理对象:

    创建实体类:

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

    数据库操作功能:

    package jdbctemplate;
    
    import java.util.List;
    
    import 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();
    }
    package 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 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;
        }
    
    
    }

    现在就完成了数据库操作,接下来配置到Spring来管理对象

    注意配置文件:

    先写一个键值对配置文件:db.properties

    jdbc.jdbcUrl=jdbc:mysql:///mybase
    jdbc.driverClass=com.mysql.jdbc.Driver
    jdbc.user=root
    jdbc.password=xuyiqing

    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.将UserDao放入spring容器 -->
    <bean name="userDao" class="jdbctemplate.UserDaoImpl" >
        <property name="dataSource" ref="dataSource" ></property>
    </bean>
        
    
    </beans>

    测试:

    package 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 bean.User;
    
    //演示JDBC模板
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:applicationContext.xml")
    public class Demo {
        @Resource(name="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());
        }
        
    }
  • 相关阅读:
    什么是JDBC的最佳实践?
    如何将jquery对象转换为js对象?
    JQuery有几种选择器?
    jQuery 库中的 $() 是什么
    JS 中 == 和 === 区别是什么?
    有两张表;请用SQL查询,所有的客户订单日期最新的前五条订单记录?
    根据你以往的经验简单叙述一下MYSQL的优化?
    数据库MySQL分页时用的语句?
    LeetCode231-2的幂(水题,考察是否粗心)
    LeetCode191-位1的个数(题目有问题)
  • 原文地址:https://www.cnblogs.com/xuyiqing/p/8465069.html
Copyright © 2020-2023  润新知