zoukankan      html  css  js  c++  java
  • JdbcTemplate常用方法

    JdbcTemplate简介

      JdbcTemplate是Spring JDBC的核心类,借助该类提供的方法可以很方便的实现数据的增删改查。

      Spring对数据库的操作在jdbc上面做了深层次的封装,使用spring的注入功能,可以把DataSource注册到JdbcTemplate之中。

      JdbcTemplate位于中。其全限定命名为org.springframework.jdbc.core.JdbcTemplate。要使用JdbcTemlate还需一个这个包包含了事务和异常控制

      

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

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

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

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

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

    xml中的配置:

    <!-- 扫描 -->
    <context:component-scan base-package="com.zzj.*"></context:component-scan>
    
    <!-- 不属于自己工程的对象用bean来配置 -->
    <!-- 配置数据库连接池 -->
    <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close" p:username="root" p:password="qw13579wq">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/test"></property>
    </bean>
    
    <!-- 配置jdbcTemplate -->
    <bean class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource-ref="dataSource"></bean>

    常用方法:

    数据库user_info表:

     我们先创建一个实体对象,对应数据库表中的信息,方便之后的查询操作

    package com.zzj.vo;
    
    public class UserInfo {
    
        private int id;
        private String userName;
        private String password;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        @Override
        public String toString() {
            return "UserInfo [id=" + id + ", userName=" + userName + ", password=" + password + "]";
        }
        
    }

    修改(包含增、删、改):update()方法,另有批量插入方法batchUpdate()

    update()方法增删改:

    UserInfoDao.java代码:

    @Repository
    public class UserInfoDao {
    
        @Autowired
            //从容器中自动扫描获取jdbcTemplate
        private JdbcTemplate jdbcTemplate;
    
            //update()实现增加数据
        public boolean insert(int id,String userName,String password){
            String sql = "insert into user_info values (?,?,?)";
            return jdbcTemplate.update(sql,id,userName,password)>0;
        }
        
        //update()实现修改
        public boolean update(int id,String userName,String password){
            String sql = "update user_info set user_name=?,password=? where id=?";
            return jdbcTemplate.update(sql,userName,password,id)>0;
        } 
        
        //update()实现删除
        public boolean delete(int id){
            String sql = "delete from user_info where id=?";
            return jdbcTemplate.update(sql,id)>0;
        }
    
    }
    

    测试类代码:

    public class Test {
    
        public static void main(String[] args) {
            
            ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
            UserInfoDao userDao = applicationContext.getBean(UserInfoDao.class);
            
            boolean insert = userDao.insert(1,"Jim", "123");
            boolean update = userDao.update(1,"Tom","123456");
            boolean delete = userDao.delete(1);
         System.out.println("插入:"+insert+",修改:"+update+",删除:"+delete);

    } }

    测试结果:

    查询:查询单个值、查询一个对象、查询多个对象

    查询单个值

    //查询单个值
    public boolean login(String userName,String password){
        try {
            String sql = "select id from user_info where user_name=? and password=?";
            jdbcTemplate.queryForObject(sql,String.class,userName,password);
            return true;
        } catch (DataAccessException e) {
            return false;
        }
    }

    查询一个对象:RowMapper方法和ResultSetExtractor方法

    //查询单个对象
    public UserInfo getById(int id){
        String sql = "select id,user_name,password from user_info where id=?";
        
        //RowMapper方法
        class UserInfoRowMapper implements RowMapper<UserInfo>{
    
            @Override
            public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
                UserInfo userInfo = new UserInfo();
                userInfo.setId(rs.getInt("id"));
                userInfo.setUserName(rs.getString("user_name"));
                userInfo.setPassword(rs.getString("password"));
                return userInfo;
            }
            
        }
        
        return jdbcTemplate.queryForObject(sql,new UserInfoRowMapper(),id);
    
        //RowMapper方法的Lambda表达式
        return jdbcTemplate.queryForObject(sql,(ResultSet rs,int rowNum)->{
            UserInfo userInfo = new UserInfo();
            userInfo.setId(rs.getInt("id"));
            userInfo.setUserName(rs.getString("user_name"));
            userInfo.setPassword(rs.getString("password"));
            return userInfo;
        },id);
        
        //ResultSetExtractor方法
        class UserInfoResultSet implements ResultSetExtractor<UserInfo>{
    
            @Override
            public UserInfo extractData(ResultSet rs) throws SQLException, DataAccessException {
                UserInfo userInfo = null;
                if(rs.next()){
                    userInfo = new UserInfo();
                    userInfo.setId(rs.getInt("id"));
                    userInfo.setUserName(rs.getString("user_name"));
                    userInfo.setPassword(rs.getString("password"));
                }
                return userInfo;
            }
        }
        return jdbcTemplate.query(sql,new UserInfoResultSet(),id);
        
        //ResultSetExtractor方法的lambda表达式
        return jdbcTemplate.query(sql,(ResultSet rs)->{
            UserInfo userInfo = null;
            if(rs.next()){
                userInfo = new UserInfo();
                userInfo.setId(rs.getInt("id"));
                userInfo.setUserName(rs.getString("user_name"));
                userInfo.setPassword(rs.getString("password"));
            }
            return userInfo;
        },id);
        
    }

    查询多个对象:RowMapper方法和ResultSetExtractor方法

    //查询多个对象
    public List<UserInfo> selectAll(){
        String sql = "select id,user_name,password from user_info";
        
        //RowMapper方法
        class UserInfoRowMapper implements RowMapper<UserInfo>{
            
            @Override
            public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
                UserInfo userInfo = new UserInfo();
                userInfo.setId(rs.getInt("id"));
                userInfo.setUserName(rs.getString("user_name"));
                userInfo.setPassword(rs.getString("password"));
                return userInfo;
            }
            
        }
        return jdbcTemplate.query(sql,new UserInfoRowMapper());
        
        
        //RowMapper方法的Lambda表达式
        return jdbcTemplate.query(sql,(ResultSet rs,int rowNum)->{
            UserInfo userInfo = new UserInfo();
            userInfo.setId(rs.getInt("id"));
            userInfo.setUserName(rs.getString("user_name"));
            userInfo.setPassword(rs.getString("password"));
            return userInfo;
        });
        
        //ResultSetExtractor方法
        class UserInfoResultSet implements ResultSetExtractor<List<UserInfo>>{
    
            @Override
            public List<UserInfo> extractData(ResultSet rs) throws SQLException, DataAccessException {
                List<UserInfo> list = new ArrayList<>();
                while(rs.next()){
                    UserInfo userInfo = new UserInfo();
                    userInfo.setId(rs.getInt("id"));
                    userInfo.setUserName(rs.getString("user_name"));
                    userInfo.setPassword(rs.getString("password"));
                    list.add(userInfo);
                }
                return list;
            }
            
        }
        return jdbcTemplate.query(sql, new UserInfoResultSet());
        
        //ResultSetExtractor方法的lambda表达式
        return jdbcTemplate.query(sql,(ResultSet rs)->{
            List<UserInfo> list = new ArrayList<>();
            while(rs.next()){
                UserInfo userInfo = new UserInfo();
                userInfo.setId(rs.getInt("id"));
                userInfo.setUserName(rs.getString("user_name"));
                userInfo.setPassword(rs.getString("password"));
                list.add(userInfo);
            }
            return list;
        });
        
    }
  • 相关阅读:
    多线程编程(2):线程的同步
    C#中listview实现排序
    [PLC]S7-300的数据类型
    C# 多线程编程(4):多线程与UI操作
    Thunderbird 80 column FIX 发出的邮件也需要在80列处line break
    vsftp 500 OOPS: vsftpd: refusing to run with writable anonymous root
    科普 What is YUV
    转载:网站真的可以无密码登录么?
    Ubuntu 12.04安装Microsoft lifecam studio摄像头
    Thunderbird on Ubuntu 12.04 调整邮件列表行间距
  • 原文地址:https://www.cnblogs.com/yimengxianzhi/p/12271543.html
Copyright © 2011-2022 走看看