Template objects in Spring

In the Spring framework, there are many template objects available. These template objects, the development of tedious and repeated part of all encapsulated, greatly simplified our development after use. At the same time, we can reduce the difficulty of getting started, so that we can achieve business requirements more simply and directly. This is also what we mentioned in our Spring Framework advantages presentation on day one of the Spring Framework course.

The Spring framework provides the following template objects:

The name of the object Where the package instructions
TransactionTemplate org.springframework.transaction.support A template object used to implement transaction control programmatically
JdbcTemplate org.springframework.jdbc.core Template object used to simplify JDBC operations
RedisTemplate org.springframework.data.redis.core A template object to simplify Redis operations
RabbitTemplate org.springframework.amqp.rabbit.core.RabbitTemplate Template object for simplifying RabbitMQ message queuing operations
JmsTemplate org.springframework.jms.core Template object for simplifying the ActiveMQ message queue
HibernateTemplate org.springframework.orm.hibernate5 Template objects to simplify working with the Hibernate framework (which is now largely unused in actual development)
RestTemplate org.springframework.web.client A template object to simplify sending REST-style requests (REST-style requests are covered in the SpringMVC course)

JdbcTemplate object

The introduction of JDBCTemplate

JDBCTemplate is a tool for simple manipulation of the persistence layer (DAO). Much like Dbutils, JDBCTemplate is a thin wrapper around JDBC.

The JDBCTemplate is provided by Spring for better integration with Spring

JdbcTemplateAPI introduction

The JDBCTemplate API is used in much the same way as QueryRunner

  • The constructor passes the DataSource object
public JdbcTemplate(DataSource DataSource) : The constructor passes the DataSource DataSource object
Copy the code
  • API methods
update(String sql, Object... Obj) : Execute insert, update, delete statements
queryForObject(String sql,RowMapper mapper,Object... Obj) : Query returns a single object, of type POJO
queryForObject(String sql,Class clazz,Object... Obj) : Query returns a single object, a primitive type and its wrapper class, and a string
query(String sql,RowMapper mapper,Object... Obj) : Query returns a collection object

supplement : RowMapper interface implementation class BeanPropertyRowMapper, the implementation of the query result set encapsulation, suitable for a single object or set of queries
Copy the code

JdbcTemplate example

pom.xml

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.9. RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.20</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9. RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.9. RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
Copy the code

Entity class

public class Account implements Serializable {

    private Integer id;
    private String name;
    private Double money;

    public Integer getId(a) {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getMoney(a) {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money; }}Copy the code

Configure Spring’s Ioc

@Configuration
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbc.properties")
public class SpringConfiguration {}Copy the code
public class JdbcConfig {

    @Value("${jdbc.driverClassName}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    /** * Create the data source and store it in the Ioc container *@return* /
    @Bean
    public DataSource createDataSource(a){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    /** * Create the JdbcTemplate object *@param dataSource
     * @return* /
    @Bean
    public JdbcTemplate createJdbcTemplate(DataSource dataSource){
        return newJdbcTemplate(dataSource); }}Copy the code
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_lx
jdbc.username=root
jdbc.password=root
Copy the code

3) Write test classes

/** * Test class */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class JdbcTemplateTest {

    // dependency injection
    @Autowired
    private JdbcTemplate jdbcTemplate;

    / / to add
    @Test
    public void save(a) {
        Account account = new Account();
        account.setName("School beauty");
        account.setMoney(6666d);

        String sql = "insert into account values(? ,? ,?) ";
        Object[] params = {account.getId(), account.getName(), account.getMoney()};

        jdbcTemplate.update(sql, params);
    }

    / / delete
    @Test
    public void deleteById(a) {
        String sql = "delete from account where id=?";

        jdbcTemplate.update(sql, 6);
    }

    / / change
    @Test
    public void update(a) {
        Account account = new Account();
        account.setId(7);
        account.setName("Xiao Ming");
        account.setMoney(66d);

        String sql = "update account set name=? , money=? where id=?";
        Object[] params = {account.getName(), account.getMoney(), account.getId()};

        jdbcTemplate.update(sql, params);
    }

    // Query by id
    @Test
    public void findById(a) {
        String sql = "select * from account where id=?";

        Account account = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Account.class), 7);
        System.out.println("account = " + account);
    }

    // Query the number of records
    @Test
    public void findByTotalCount(a) {
        String sql = "select count(1) from account";

        Integer count = jdbcTemplate.queryForObject(sql, int.class);
        System.out.println("count = " + count);
    }

    // Query all
    @Test
    public void findAll(a) {
        String sql = "select * from account";

        List<Account> accountList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Account.class));
        for (Account account : accountList) {
            System.out.println("account = "+ account); }}Pojo = poJO = poJO = poJO = poJO
    @Test
    public void findAll2(a) {
        String sql = "select id ids, name names, money moneys from account";

        List<Account> accountList = jdbcTemplate.query(sql, new RowMapper<Account>() {
            @Override
            public Account mapRow(ResultSet resultSet, int index) throws SQLException {
                Account account = new Account();
                // Assign a value to the current account object
                account.setId( resultSet.getInt("ids")); account.setName( resultSet.getString("names")); account.setMoney( resultSet.getDouble("moneys"));returnaccount; }});for (Account account : accountList) {
            System.out.println("account = "+ account); }}}Copy the code