• Spring | Spring的“数据库开发“ (Srping JDBC)


    在这里插入图片描述

    作者简介 :一只大皮卡丘,计算机专业学生,正在努力学习、努力敲代码中! 让我们一起继续努力学习!

    该文章参考学习教材为:
    《Java EE企业级应用开发教程 (Spring + Spring MVC +MyBatis)》 黑马程序员 / 编著
    文章以课本知识点 + 代码为主线,结合自己看书学习过程中的理解和感悟 ,最终成就了该文章

    文章用于本人学习使用 , 同时希望能帮助大家。
    欢迎大家点赞👍 收藏⭐ 关注💖哦!!!

    (侵权教材方可联系我,进行删除,如果雷同,纯属巧合)


    Spring JDBC

    SpringJDBC模块 负责数据库资源管理错误处理,大大简化了开发人员对数据库的操作,使得开发人员可以从烦琐的数据库操作中解脱出来,从而将更多的精力投入到编写业务逻辑中

    1.Spring JDBC的核心类 ( JdbcTemplate类 )

    • 针对数据库的操作,Spring 框架 (Spring JDBC )提供了 JdbcTemplate类,该类是Spring框架数据抽象层基础,其他更高层次的抽象类却是构建于JdbcTemplate类之上。

    • JdbcTemplate 类是Spring JDBC核心类

    • JdbcTemplate继承 / 实现 关系为 :
      在这里插入图片描述

      抽象类赋予JdbcTemplate属性接口赋予JdbcTemplate操作的方法,具体内容如下 :
      一、
      JdbcTemplate 继承 抽象类 JdbcAccessorJdbcAccessor是 JdbcTemplate的直接父类 (JdbcAccessor) 为子类 (JdbcTemplate) 提供了一些访问数据库时使用公共属性

      DataSource : 其主要功能是获取数据库连接具体实现时还可以引入对数据库连接
      冲池分布式事务的支持,它可以作为访问数据库资源的标准接口。

      SQLExceptionTranslator
      org.springframework.jdbc support.SQLExceptionTranslator接口负责对 SQLException 进行转译工作。通过必要的设置或者 获取SQLExceptionTranslator中的方法,可以使 JdbcTemplate 在需要处理SQLException时,委托SQLExceptionTranslator实现类完成相关的转译工作

      二、
      JdbcTemplate 实现了 JdbcOperations 接口。JdbcOperations接口定义了在JdbcTemplate类中可以使用的操作集合,包括 添加修改查询删除 等操作。

    2.Srping JDBC 的配置

    • Spring JDBC模块主要由 4个包组成,分别是core (核心包)dataSource (数据源包)object (对象包)support (支持包)

    • 想实现 Spring JDBC功能,要进行Spring JDBC配置 :
      配置 core (核心包) 中的 JdbcTemplate 类
      配置 dataSource (数据源包) 中的 DriverManagerDataSource类
      (在 applicationContext.xml 中进行配置)

    • 包名说明
      core包
      (要配置JdbcTemplate 类)
      包含了JDBC核心功能,包括 JdbcTemplate 类SimpleJdbcInsert类SimpleJdbcCall类 以及 NamedParameterJdbcTemplate类
      ② 定义JdbcTemplate时,要将已经配置好的dataSource注入到JdbcTemplate中。
      dataSource包
      (要配置dataSource数据源 : DriverManagerDataSource类 )
      访问数据源实用工具类,它有多种数据源实现,可以在Java EE容器外部测试JDBC代码。
      ② 在配置文件中配置dataSource其的类为 :org.springframework.jdbc.datasource.DriverManagerDataSource
      ③ 配置 dataSource4个属性分别为: 数据库驱动url用户名密码
      ps : 配置dataSource的例子在下面。
      object包面向对象的方式访问数据库,它允许执行查询并将返回结果作为业务对象,可以在数据表的列业务对象的属性之间映射查询结果
      support包包含了coreobject包支持类,例如,提供异常转换功能的SQLException类
    • dataSource4个属性
      ( 在以下的dataSource4个属性applicationContext.xml中完成配置 )

      属性名含义
      driverClassName使用驱动名词,对应驱动JAR包中工的Driver类
      如 :name=“driverClassNamevalue=“com.mysql.jdbc.Driver”/>
      url数据源所在地址
      如 :name=“urlvalue=“jdbc:mysql://localhost:3306/spring”/>
      username访问数据库的用户名
      如:
      password访问数据库的密码
      如 :
    • Srping JDBC配置的 “配置模板” / 例子
      Spring JDBC要添 JAR包 : (配置JAR包)
      Spring的核心JAR包

      Spring JDBC开发所需JARmysql数据库的驱动JAR包 (mysql-connector-java.jar) 、Srpring的JDBC的JAR包 (spring-jdbc.jar) 、Spring事务处理的JAR包(spring-tx.jar)。

      在这里插入图片描述

      获取spring框架基本核心jar包
      获取Spring JDBC 开发需要的jar包
      jar包 / maven( 依赖 ) 下载( 可自行按需下载JAR )
      ps :
      如有报错版本问题,可看情况判断是否需要更换JAR版本


      applicationContext.xml

    
    <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    
    
    
    <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"/>
      
      <property name="username" value="root"/>
      
      <property name="password" value="root"/>
    bean>
    
    
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
      
      <property name="dataSource" ref="dataSource"/>
    bean>
    
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    在上述applicationContext.xml中,定义了 3个Bean,分别是 dataSourejdbcTemplate需要注入类Bean
    其中 dataSource 对应 的org.springframework.jdbc.datasource. DriverManagerDataSource 类用于对数据源进行配置
    jdbcTemplate 对应的org.springframework.jdbc.core. JdbcTemplate 类用于定义了JdbcTemplate的相关配置。

    dataSource4个属性,需要根据数据库类型或者机器配置的不同设置相应的属性值。例如果数据库类型不同需要更改驱动名称;如果数据库不在本地,则需要将地址中的 localhost 替换成相应的主机IP;如果修改过MySQL数据库的端口号(默认为3306),则需要加上修改后的端口号,如果没修改,则端口号可以省略。

    3.JdbcTemplate类的“常用方法”

    JdbcTemplate类中,提供了大量的更新查询数据库方法,我们就是使用这些方法操作数据库的。

    execute( ):直接执行“sql语句”,没有返回值
    • execute (String sql) 方法 : 执行指定的 SQL 语句。该方法是==没有返回值==的。

      例子如 :

      第一步、建好项目、导入所需依赖、打开doc窗口,指定确定存在数据库 (如: use spring)
      在这里插入图片描述

      在这里插入图片描述

      ​ 此时spring这个 “数据库” 中并没有 “数据表”。

      第二步、配置applicationContext.xml

      
      <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
      
          
      
          
          <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"/>
              
              <property name="username" value="root"/>
              
              <property name="password" value="root"/>
          bean>
      
          
          <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
              
              <property name="dataSource" ref="dataSource"/>
          bean>
      
      beans>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28

      第三步、创建 JdbcTemplateTest测试类测试 JdbcTemplate类中的 execute( )方法的使用情况 :

      package com.myh.jdbc;
      
      import org.springframework.context.ApplicationContext;
      import org.springframework.context.support.ClassPathXmlApplicationContext;
      import org.springframework.jdbc.core.JdbcTemplate;
      
      public class JdbcTemplateTest { //在该测试类中使用 execute()方法建数据库中的"表"
          public static void main(String[] args) {
              //加载配置文件
              ApplicationContext applicationContext =
                      new ClassPathXmlApplicationContext("com/myh/jdbc/applicationContext.xml");
              //从IOC容器中获得 JdbcTemplate 实例
              JdbcTemplate jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
      
              String sql = "create table student(" +
                      "id int primary key auto_increment," +
                      "username varchar(50)," +
                      "hobby varchar(50))";
              /*
                execute()方法作用 : 执行sql语句
               */
              jdbcTemplate.execute(sql);
              System.out.println("创建student表成功!");
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25

      运行效果图
      doc窗口,输入 “show tables”命令,判断execute( )方法是否成功执行

    在这里插入图片描述

    控制台输入 如下 :

    在这里插入图片描述

    由两个效果图可知,程序 使用execute( String sql )方法执行的sql语句成功创建student表

    update( ) :“增删改”,返回 “影响的行数”
    • update()方法 : 可以完成 插入更新删除数据 的操作,有返回值 : 返回影响的行数
      JdbcTemplate类中,提供了一系列的
      update( )方法,其常用方法如下所示 :
    方法说明
    int update( String sql )该方法是最简单update 方法重载形式,它直接执行传入的SQL语句,并 返回受影响行数
    int update( PreparedStatementCreator psc )该方法执行PreparedStatementCreator返回的语句,然后返回受影响的行数
    int update( String sql,PreparedStatementSetter )该方法通过PreparedStatementSetter设置SQL语句中参数,并返回受影响的行数
    int update( String sql,Object…args )
    ★★★★★ ( 常用 )
    该方法 使用Object…设置SQL语句中参数要求参数不能为NULL,并 返回受影响的行数
    将设置的参数填充到占位符?中

    update( ) 方法例子 :进行“增删改”操作。
    Student.java

    package com.myh.jdbc;
    
    public class Student {
        private Integer id; //学生id
        private String username; //用户名
        private String hobby;
    
         /*
          getter/setter方法
         */
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getHobby() {
            return hobby;
        }
    
        public void setHobby(String hobby) {
            this.hobby = hobby;
        }
    
        //重写toString()方法
        @Override
        public String toString() {
            return "Student{" +
                    "id=" + id +
                    ", username='" + username + '\'' +
                    ", hobby='" + hobby + '\'' +
                    '}';
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    StudentDao.java (接口) :

    package com.myh.jdbc;
    
    public interface StudentDao {  //在该接口中定义“添加”、“更新”、“删除”的Student的方法
        //添加
        public int addStudent(Student student);
        //更新
        public int updateStudent(Student student);
        //删除
        public int deleteStudent(int id);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    StudentDaoImpl.java实现类

    package com.myh.jdbc;
    
    import org.springframework.jdbc.core.JdbcTemplate;
    public class StudentDaoImpl implements StudentDao{ //该类为StudentDao接口的"实现类"
    
        //声明JdbcTemplate属性
        private JdbcTemplate jdbcTemplate;
    
        //为JdbcTemplate属性 添加setter方法
        public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
            this.jdbcTemplate = jdbcTemplate;
        }
    
        /**
          添加
         */
        @Override
        public int addStudent(Student student) {
            /*
              sql语句,此处的占位符?通过下面的Object参数进行填充
             */
            String sql = "insert into student(username,hobby) values(?,?)";
            //定义数组来存储sql语句中的参数 (将Student类中存储的数组放进数组中)
            Object[] obj = new Object[]{student.getUsername(),student.getHobby()};
            //通过 update(String sql)执行操作,返回值为: sql语句影响的行数
            int num = this.jdbcTemplate.update(sql,obj); //返回sql语句影响的行数
            return num;
        }
    
        /**
         * 更新
         */
        @Override
        public int updateStudent(Student student) {
            String sql = "update student set username = ?,hobby = ? where id = ?";
            //定义要用在update()方法中的参数
            Object[] params = new Object[]{student.getUsername(), student.getHobby(), student.getId()};
            int num = this.jdbcTemplate.update(sql, params);
            return num;
        }
    
        /**
         * 删除
         */
        @Override
        public int deleteStudent(int id) {
            String sql = "delete from student where id = ?";
            //执行删除操作,返回影响的行数
            int num = this.jdbcTemplate.update(sql, id);
            return num;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52

    applicationContext.xml

    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        
    
        
        <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"/>
            
            <property name="username" value="root"/>
            
            <property name="password" value="root"/>
        bean>
    
        
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            
            <property name="dataSource" ref="dataSource"/>
        bean>
    
       
        <bean id="studentDao" class="com.myh.jdbc.StudentDaoImpl">
            <property name="jdbcTemplate" ref="jdbcTemplate"/>
        bean>
    
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    JdbcTemplateTest.java (测试类)

    package com.myh.jdbc;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.jdbc.core.JdbcTemplate;
    
    public class JdbcTemplateTest { //在该测试类中使用 execute()方法建数据库中的"表"
        
        /**
         * 进行Junit测试
         */
        @Test
        public void JunitTest() {
            //加载配置文件
            ApplicationContext applicationContext =
                    new ClassPathXmlApplicationContext("com/myh/jdbc/applicationContext.xml");
            //从IOC容器中获得 JdbcTemplate 实例
            JdbcTemplate jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
    
            /*
              execute()方法作用 : 执行sql语句
             */
            jdbcTemplate.execute("select * from tb_user");
            System.out.println("数据查询成功!");
        }
    
    
        /**
         * 添加
         */
       @Test //junit4单元测试
       public void addStudentTest() {
           //加载配置文件
           ApplicationContext applicationContext =
                   new ClassPathXmlApplicationContext("com/myh/jdbc/applicationContext.xml");
           //获取StudentDao实例
           StudentDao studentDao = (StudentDao) applicationContext.getBean("studentDao");
           //创建Student对象,往其中添加数据
           Student student = new Student();
           student.setUsername("张三");
           student.setHobby("打篮球");
           //添加
           int num = studentDao.addStudent(student);
           if (num > 0) {
               System.out.println("成功插入了" + num + "条数据!");
           } else {
               System.out.println("插入操作执行失败!");
           }
       }
    
        /**
         * 更新(修改)
         */
        @Test
        public void updateStudentTest() {
            //加载配置文件
            ApplicationContext applicationContext =
                    new ClassPathXmlApplicationContext("com/myh/jdbc/applicationContext.xml");
            //获取StudentDao实例
            StudentDao studentDao = (StudentDao) applicationContext.getBean("studentDao");
            //创建Student对象,往其中添加数据
            Student student = new Student();
            student.setId(1);
            student.setUsername("小明");
            student.setHobby("踢足球");
            //更新(修改)
            int num = studentDao.updateStudent(student);
            if (num > 0) {
                System.out.println("成功修改了" + num + "条数据!");
            } else {
                System.out.println("修改操作执行失败!");
            }
        }
    
    
        /**
         * 删除
         */
        @Test
        public void deleteStudentTest() {
            //加载配置文件
            ApplicationContext applicationContext =
                    new ClassPathXmlApplicationContext("com/myh/jdbc/applicationContext.xml");
            //获取StudentDao实例
            StudentDao studentDao = (StudentDao) applicationContext.getBean("studentDao");
            //删除
            int num = studentDao.deleteStudent(1);
            if (num > 0) {
                System.out.println("成功删除了" + num + "条数据!");
            } else {
                System.out.println("删除操作执行失败!");
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    query( ) : “查询”,返回 “T类型 / List类型” 的结果
    • query( ) : 数据库中的数据进行查询操作
      JdbcTemplate类中还提供了大量的query( )方法来处理各种对数据库表查询操作

      方法说明
      List query ( String sql , RowMapper rowMapper)
      ★★★★★ ( 常用 )
      执行String类型参数提供SQL语句,并通过 RowMapper 返回一个List类型结果
      :
      可用于查询所有数据。(★★★)
      List query ( String sql , PearesSatementSetter pss , RowMapper rowMapper)根据String 类型参数提供SQL语句创建 PreparedStatement对象,通过RowMapper结果 / 结果集返回到List中。
      List query ( String sql , Objecr[ ] args , RowMapper rowMapper )使用Obiect[ ]的值来设置SQL语句中的参数值,采用 RowMapper回调方法可以直接返回List类型数值
      T queryForObject ( String sql , RowMapper rowMapper ,
      Object… args)
      ★★★★★ ( 常用 )
      args参数绑定SQL语句中,并通过 RowMapper 返回一个Object类型单行记录
      :
      用于“根据指定id查询数据。(★★★)
      List queryForList ( String sql , Object[ ] args , class )该方法可以 返回多行数据结果, 但必须是返回列表elementType参数返回的是 List元素类型
    • query( ) 方法例子 :返回 “T类型 / List类型” 的结果 :

      Student.java

      package com.myh.jdbc;
      
      public class Student {
          private Integer id; //学生id
          private String username; //用户名
          private String hobby;
      
           /*
            getter/setter方法
           */
          public Integer getId() {
              return id;
          }
      
          public void setId(Integer id) {
              this.id = id;
          }
      
          public String getUsername() {
              return username;
          }
      
          public void setUsername(String username) {
              this.username = username;
          }
      
          public String getHobby() {
              return hobby;
          }
      
          public void setHobby(String hobby) {
              this.hobby = hobby;
          }
      
          //重写toString()方法
          @Override
          public String toString() {
              return "Student{" +
                      "id=" + id +
                      ", username='" + username + '\'' +
                      ", hobby='" + hobby + '\'' +
                      '}';
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44

      StudentDao.java (接口)

      package com.myh.jdbc;
      
      import java.util.List;
      
      public interface StudentDao { 
      
          //根据id查询
          public Student findStudentById(int id);
          //查询所有
          public List<Student> findAllStudent();
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11

      StudentDaoImpl.java (实现类)

      package com.myh.jdbc;
      
      import org.springframework.jdbc.core.BeanPropertyRowMapper;
      import org.springframework.jdbc.core.JdbcTemplate;
      import org.springframework.jdbc.core.RowMapper;
      
      import java.util.List;
      
      public class StudentDaoImpl implements StudentDao{ //该类为StudentDao接口的"实现类"
      
          /**
           *  根据id查询 :
           *  用queryForObject ( String sql , RowMapper rowMapper , Object...args) 这个方法来进行“根据id”查询数据
           *  该方法 : 将args参数绑定到sql语句中,且通过 RowMapper 返回一个Object类型的“单行记录”。
           */
          @Override
          public Student findStudentById(int id) {
              //sql语句
              String sql = "select * from student where id = ?";
              //创建一个BeanPropertyRowMapper对象
              RowMapper<Student> rowMapper = new BeanPropertyRowMapper<Student>(Student.class);
              //调用query()方法查询数据库中的数据
              Student student = this.jdbcTemplate.queryForObject(sql, rowMapper, id); //返回值为一个
              return student;
      }
      
      
          /**
           * 查询所有
           */
          @Override
          public List<Student> findAllStudent() {
              //sql语句
              String sql = "select * from student";
              //创建 BeanPropertyRowMapper 对象
              RowMapper<Student> rowMapper = new BeanPropertyRowMapper<Student>(Student.class);
              List<Student> students = this.jdbcTemplate.query(sql, rowMapper); //返回值为list集合,该集合中存储一个或多个Student类数据
              return students;
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40

      applicationContext.xml

    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        
    
        
        <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"/>
            
            <property name="username" value="root"/>
            
            <property name="password" value="root"/>
        bean>
    
        
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            
            <property name="dataSource" ref="dataSource"/>
        bean>
    
       
        <bean id="studentDao" class="com.myh.jdbc.StudentDaoImpl">
            <property name="jdbcTemplate" ref="jdbcTemplate"/>
        bean>
    
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    JdbcTemplateTest.java (测试类)

    package com.myh.jdbc;
    	
    import org.junit.Test;
    	import org.springframework.context.ApplicationContext;
    	import org.springframework.context.support.ClassPathXmlApplicationContext;
    	import org.springframework.jdbc.core.JdbcTemplate;
    import java.util.Iterator;
    import java.util.List;
    
    public class JdbcTemplateTest { 
    
        /**
         * 根据id来查询数据
         */
        @Test
        public void findStudentByIdTest() {
            //加载配置文件
            ApplicationContext applicationContext =
                    new ClassPathXmlApplicationContext("com/myh/jdbc/applicationContext.xml");
            //获取StudentDao实例
            StudentDao studentDao = (StudentDao) applicationContext.getBean("studentDao");
            //执行 findStudentById()方法
            Student student = studentDao.findStudentById(1);
            System.out.println(student);
        }
        
         /**
         * 查询所有数据
         */
        @Test
        public void findAllStudentTest() {
            //加载配置文件
            ApplicationContext applicationContext =
                    new ClassPathXmlApplicationContext("com/myh/jdbc/applicationContext.xml");
            //获取StudentDao实例
            StudentDao studentDao = (StudentDao) applicationContext.getBean("studentDao");
            //执行 findAllStudent()方法
            List<Student> allStudent = studentDao.findAllStudent();
    //使用“集合”的“迭代器”遍历集合中数据
            Iterator<Student> iterator = allStudent.iterator();
    while (iterator.hasNext()) {
                Student next = iterator.next();
                System.out.println(next);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
  • 相关阅读:
    stl中vecter和pair组合达到字典的效果
    滑动窗口的理念
    往USBKey里面导入双证书专题:概念介绍、执行逻辑
    vue+elementUI
    10.力扣c++刷题-->罗马数字转整数
    C Primer Plus(6) 中文版 第7章 C控制语句:分支和跳转 7.6 循环辅助:continue和break
    【Lua 入门基础篇(六)】数组&迭代器
    非洲美食多样性而丰富多彩
    Nginx基础篇-Nginx的编译参数
    常见 HTTP 状态码详解与Nginx 文件上传大小限制
  • 原文地址:https://blog.csdn.net/m0_70720417/article/details/135943421