zoukankan      html  css  js  c++  java
  • Spring JdbcTemplate的使用秘籍

    首先要引入

    <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>5.2.3.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>5.2.3.RELEASE</version>
        </dependency>
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>8.0.17</version>
        </dependency>
    

    再配置一下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:aop="http://www.springframework.org/schema/aop"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           https://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/aop
           https://www.springframework.org/schema/aop/spring-aop.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx.xsd">
    
         <!--配置mysql-->
         <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
              <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
              <property name="url" value="jdbc:mysql://localhost:3306/spring?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=utf-8"/>
              <property name="username" value="root"/>
              <property name="password" value="你自己的数据库密码"/>
         </bean>
         <!--配置jdbc templete-->
         <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
         <property name="dataSource" ref="dataSource"/>
         </bean>
    
    
    </beans>
    

    定义一个学生类:Student,数据库中有Student表,进行测试

    package com.ibuyi.free.spring.jdbc;
    
    public class Student {
        private int id;
        private String name;
        private String sex;
        private String born;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    
        public String getBorn() {
            return born;
        }
    
        public void setBorn(String born) {
            this.born = born;
        }
    
        @Override
        public String toString() {
            return "{" +id+' '+name+' '+sex+' '+born+
                    "}";
        }
    }
    
    
    package com.ibuyi.free.spring.jdbc;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.jdbc.core.RowMapper;
    
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    
    public class JdbcTest {
        private JdbcTemplate jdbcTemplate;
        {
            ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
            jdbcTemplate= (JdbcTemplate) context.getBean("jdbctemplate");
        }
    
        public void test(){
          //首先创建一张表
            String sql="create table test(id int,name varchar(20))";
            jdbcTemplate.execute(sql);
    
        }
        @Test
        public void test1(){
            //查询一个数据
            String sql = "select count(*) from student";
            int count=jdbcTemplate.queryForObject(sql,Integer.class);
            System.out.println(count);
        }
    
    
        public void test2(){
            //更新一条数据
            String sql="update student set sex=? where id=?";
            int count = jdbcTemplate.update(sql,"女",1);
            System.out.println(count);
        }
    
        @Test
        public void test3(){
            //插入一条数据
            String sql = "insert into student(name,sex,born) values(?,?,?)";
            int count =jdbcTemplate.update(sql,"zhang","男","1999-07-16");
            System.out.println(count);
        }
    
    
        public void test4(){
            String []sql={
            //批量插入
            "insert into student(name,sex,born) values('zhang','女','1999-07-16')",
            "insert into student(name,sex,born) values('bei','女','1999-07-16')",
            "insert into student(name,sex,born) values('di','女','1999-07-16')"
           };
            int[] count =jdbcTemplate.batchUpdate(sql);
            System.out.println(count);
        }
        @Test
        public void test5(){
            //执行同构sql
            String sql="insert into course(name,score) values(?,?)";
            List<Object[]> list=new ArrayList<>();
            list.add(new Object[]{"Java",80});
            list.add(new Object[]{"MySQL",100});
            list.add(new Object[]{"JavaEE",90});
    
            int[] count=jdbcTemplate.batchUpdate(sql,list);
            System.out.println(count[0]);
    
        }
    
        @Test
        public void test6(){
            //执行查询
            String sql = "select name from student where sex=?";
            List<String> list = jdbcTemplate.queryForList(sql,String.class,"女");
            System.out.println(list);
    
        }
    
        public void test7(){
            //查询一条复杂对象
            String sql = "select * from student where id=?";
            Map<String,Object> map=jdbcTemplate.queryForMap(sql,1);
            System.out.println(map);
    
        }
    
        @Test
        public void test8(){
            //查询多条负责对象
            String sql = "select * from student where sex=?";
            List<Map<String,Object>> map=jdbcTemplate.queryForList(sql,"女");
            System.out.println(map);
    
        }
        @Test
        public void test9(){
            //查询一个复杂对象,封装为实体对象
            String sql = "select * from student where id=?";
            Student students= (Student) jdbcTemplate.queryForObject(sql,new StudentRowMaper(),1);
            System.out.println(students);
    
    
        }
    
        @Test
        public void test10(){
            //查询多个复杂对象,封装为实体对象
            String sql = "select * from student where sex=?";
            List<Student> students = jdbcTemplate.query(sql,new StudentRowMaper(),"女");
            for(Student student:students){
                System.out.println(student);
            }
    
    
    
        }
    
        private class StudentRowMaper implements RowMapper{
    
            @Override
            public Object mapRow(ResultSet resultSet, int i) throws SQLException {
                Student student=new Student();
                student.setName(resultSet.getString("name"));
                student.setId(resultSet.getInt("Id"));
                student.setSex(resultSet.getString("sex"));
                student.setBorn(resultSet.getString("born"));
                return student;
            }
        }
    
    
    }
    
    
  • 相关阅读:
    快速获取JOB运行结果
    快速获取DB服务器当前 MEM CPU的资源消耗
    Mongodb Sharding+Replica Set
    MongoDB replSet
    Journal工作原理
    Oracle索引梳理系列(八)- 索引扫描类型及分析(高效索引必备知识)
    Oracle索引梳理系列(七)- Oracle唯一索引、普通索引及约束的关系
    Oracle索引梳理系列(六)- Oracle索引种类之函数索引
    Oracle索引梳理系列(五)- Oracle索引种类之表簇索引(cluster index)
    Oracle索引梳理系列(四)- Oracle索引种类之位图索引
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13309409.html
Copyright © 2011-2022 走看看