Spring Boot2 series of tutorials (XIX) Spring Boot integration JdbcTemplate

In the Java world, there are a few common data persistence solution, there comes JdbcTemplate Spring, MyBatis there, as well as JPA, in these scenarios, the simplest is the JdbcTemplate Spring comes, though this thing is not so MyBatis convenient, but compared to the beginning of Jdbc have been a lot stronger, and it is no less powerful MyBatis function, of course, also means that it is relatively simple to use, in fact, JdbcTemplate probably the most simple data persistence solution, the paper and everyone it said the use of this thing.

Basic configurations

JdbcTemplate basic usage is actually quite simple, the developers when creating a SpringBoot project, in addition to select the basic Web dependent, then remember elected Jdbc dependent, and can rely on database-driven, as follows:

After the project is successfully created, remember to add a database connection pool Druid dependent (Note that this can be added specifically for the Spring Boot to build druid-spring-boot-starter, rather than the Druid we generally added in the SSM), all depend added as follows:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.27</version>
    <scope>runtime</scope>
</dependency>

After the project is created, then only need to provide basic data can be configured in application.properties as follows:

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.url=jdbc:mysql:///test01?useUnicode=true&characterEncoding=UTF-8

So after all the configuration even completed, then you can use JdbcTemplate directly? Ye so easy to do? In fact, this configuration is automated SpringBoot benefits, let's say that usage, it will be a principle.

2. Basic Usage

First, we create a User Bean, as follows:

public class User {
    private Long id;
    private String username;
    private String address;
    //省略getter/setter
}

UserService then create a class, the injection JdbcTemplate UserService class as follows:

@Service
public class UserService {
    @Autowired
    JdbcTemplate jdbcTemplate;
}

Okay, so after the preparatory work is complete.

2.1 increase

In JdbcTemplate, in addition to a few API queries outside, additions and deletions are unified to use update operations themselves can pass SQL. Such as adding data, as follows:

public int addUser(User user) {
    return jdbcTemplate.update("insert into user (username,address) values (?,?);", user.getUsername(), user.getAddress());
}

The return value update method is that the number of rows affected by the SQL execution.

Here only you need to pass SQL can, if you need more complex, for example, hope to achieve a primary key in data into the backfill process, you can use PreparedStatementCreator, as follows:

public int addUser2(User user) {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    int update = jdbcTemplate.update(new PreparedStatementCreator() {
        @Override
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement("insert into user (username,address) values (?,?);", Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getAddress());
            return ps;
        }
    }, keyHolder);
    user.setId(keyHolder.getKey().longValue());
    System.out.println(user);
    return update;
}

In fact here it is equivalent to fully use the JDBC in solution, first passed in Statement.RETURN_GENERATED_KEYS when building PreparedStatement, then pass KeyHolder, eventually acquiring id just insert the data saved to the user object from KeyHolder the id attribute go with.

You can think of JDBC usage here can achieve, JdbcTemplate Spring offer, although not as MyBatis, but still a lot easier than Jdbc of.

2.2 deleted

Delete also use the update API, you can pass your SQL:

public int deleteUserById(Long id) {
    return jdbcTemplate.update("delete from user where id=?", id);
}

Of course, you can also use PreparedStatementCreator.

Change 2.3

public int updateUserById(User user) {
    return jdbcTemplate.update("update user set username=?,address=? where id=?", user.getUsername(), user.getAddress(),user.getId());
}

Of course, you can also use PreparedStatementCreator.

2.4 check

Query, then a little bit of change, everyone here mainly to introduce the query method, for example, a query for all users:

public List<User> getAllUsers() {
    return jdbcTemplate.query("select * from user", new RowMapper<User>() {
        @Override
        public User mapRow(ResultSet resultSet, int i) throws SQLException {
            String username = resultSet.getString("username");
            String address = resultSet.getString("address");
            long id = resultSet.getLong("id");
            User user = new User();
            user.setAddress(address);
            user.setUsername(username);
            user.setId(id);
            return user;
        }
    });
}

When a query needs to provide a RowMapper, is the need to manually map the attribute fields in the database and object-one correspondence up, so. . . . Ah looks a bit of trouble, in fact, if the name field in the database and object properties exactly the same, then there is another simple solution, as follows:

public List<User> getAllUsers2() {
    return jdbcTemplate.query("select * from user", new BeanPropertyRowMapper<>(User.class));
}

As time passed the query parameter is a placeholder, the foregoing and consistent, not repeat them here.

2.5 Other

In addition to these basic usage, JdbcTemplate also support other uses, such as calling a stored procedure, these are relatively easy and are relatively similar and Jdbc itself, will not be discussed here, are interested can leave a message discussion.

3. Principle Analysis

So after SpringBoot, the complete configuration database basic information, there is a JdbcTemplate, this stuff is coming from? Source code org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfigurationclass, which source code is as follows:

@Configuration
@ConditionalOnClass({ DataSource.class, JdbcTemplate.class })
@ConditionalOnSingleCandidate(DataSource.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcTemplateAutoConfiguration {
    @Configuration
    static class JdbcTemplateConfiguration {
        private final DataSource dataSource;
        private final JdbcProperties properties;
        JdbcTemplateConfiguration(DataSource dataSource, JdbcProperties properties) {
            this.dataSource = dataSource;
            this.properties = properties;
        }
        @Bean
        @Primary
        @ConditionalOnMissingBean(JdbcOperations.class)
        public JdbcTemplate jdbcTemplate() {
            JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource);
            JdbcProperties.Template template = this.properties.getTemplate();
            jdbcTemplate.setFetchSize(template.getFetchSize());
            jdbcTemplate.setMaxRows(template.getMaxRows());
            if (template.getQueryTimeout() != null) {
                jdbcTemplate
                        .setQueryTimeout((int) template.getQueryTimeout().getSeconds());
            }
            return jdbcTemplate;
        }
    }
    @Configuration
    @Import(JdbcTemplateConfiguration.class)
    static class NamedParameterJdbcTemplateConfiguration {
        @Bean
        @Primary
        @ConditionalOnSingleCandidate(JdbcTemplate.class)
        @ConditionalOnMissingBean(NamedParameterJdbcOperations.class)
        public NamedParameterJdbcTemplate namedParameterJdbcTemplate(
                JdbcTemplate jdbcTemplate) {
            return new NamedParameterJdbcTemplate(jdbcTemplate);
        }
    }
}

From this class, generally it can be seen, and when present DataSource class JdbcTemplate current path, the class is automatically configured, the jdbcTemplate said method, if the developer does not own a JdbcOperations example, the system will automatically configure a JdbcTemplate Bean (JdbcTemplate is an implementation JdbcOperations interface). Well, I do not know everyone there is no harvest it?

Public concern number one o'clock the rain [southern], focusing on the Spring Boot + Micro service and front and rear ends of separation full stack technology, video tutorials on a regular basis to share concerns reply after Java, Java dry Song Ge receive carefully prepared for you!

Guess you like

Origin www.cnblogs.com/lenve/p/11790613.html