Sping JdbcTemplate

JdbcTemplate overview

JdbcTemplate is the core class in the Spring JDBC core package (core). It can obtain database-related information through configuration files, annotations, Java configuration classes, etc., and realizes driver loading, connection opening and closing, and connection opening and closing during the JDBC development process. Encapsulation of SQL statement creation and execution, exception handling, transaction processing, data type conversion and other operations. We can easily perform JDBC programming by passing in SQL statements and necessary parameters.

Development steps

  1. Import spring-jdbc and spring-tx coordinates

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.3.6</version>
    </dependency>
    
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.3.6</version>
    </dependency>
    
  2. Create database tables and entity objects

  3. Create jdbctemplate object

  4. Perform database operations

        public  void  test1() throws PropertyVetoException {
    //        创建一个数据源对象
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            dataSource.setDriverClass("com.mysql.jdbc.Driver");
            dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
            dataSource.setUser("root");
            dataSource.setPassword("123456");
    //		创建jdbctemplate对象
            JdbcTemplate jdbcTemplate = new JdbcTemplate();
    //        设置数据源对象,知道数据库在哪里
            jdbcTemplate.setDataSource(dataSource);
    //        执行操作
            jdbcTemplate.update("insert into account values (?,?)","tom",5000);
            
            
        }
    

Use spring to generate jdbctemplate objects (create a data source bean instance and inject it into the jdbctemplate instance, and then obtain it through the spring container)

In order to make the decoupling more thorough, you can also extract the relevant configuration information into a separate configuration file. I have written it many times before and I won’t say more.

Common operations

Modification (including update, delete, insert):

jdbcTemplate.update("insert into account values (?,?)","tom",5000);

Inquire:

//         查询多个对象
//        Account是你要封装的实类的泛型
        List<Account> query = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
//        查询一个对象
        jdbcTemplate.queryForObject("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account),"tom")
//        聚合查询
        Long aLong = jdbcTemplate.queryForObject("select count(*) from account ", Long.class);

 

Guess you like

Origin blog.csdn.net/2301_78834737/article/details/131990536