Spring Boot uses JdbcTemplate (transfer)

Original address: http://blog.csdn.net/liuziyingbeidou/article/details/53561792

This is mainly for the description of some content in execute and batchUpdate. 
  For the insertion of large amounts of data, it is recommended to use batch insertion to improve performance. After actual combat, it is shown that the efficiency of batch insertion of JdbcTemplate is higher than that of circular single insertion. 
  JdbcTemplate inherits the JdbcAccessor class and the JdbcOperations interface; the JdbcAccessor class sets the data source, and JdbcOperations defines the method JdbcTemplate to implement.

1. JdbcTemplate mainly provides the following five types of methods:

  • execute method: can be used to execute any SQL statement, generally used to execute DDL statements;

  • Update method and batchUpdate method: The update method is used to execute statements such as adding, modifying, and deleting; the batchUpdate method is used to execute batch-related statements;

  • query method and queryForXXX method: used to execute query related statements;

  • call method: used to execute stored procedures, function-related statements.

2. Add corresponding modules to maven

<!--mysql 驱动-->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.40</version>
  </dependency>
  <!--支持jdbc-->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
  </dependency>
#mysql数据源
spring.datasource.url=jdbc:mysql://192.168.*.*:3306/venus_spb?useUnicode=true&amp;characterEncoding=UTF-8
spring.datasource.username=****
spring.datasource.password=*****
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

4. Inject a JdbcTemplate instance into the Service class

@Service
public class UserServiceImpl implements UserService {

    //JdbcTemplate注入实例
    @Resource
    private JdbcTemplate jdbcTemplate;
}

5. Example description

5.1 Query returns entity List
@Override
public List<UserDto> queryUsers() {
   RowMapper<UserDto> rm = BeanPropertyRowMapper.newInstance(UserDto.class);
   List<UserDto> userList = jdbcTemplate.query("select * from vns_user",rm);
   //userList = jdbcTemplate.queryForList("select * from vns_user",UserDto.class);
   return userList;
}

Special note: The query using queryForList is abnormal, because UserDto.class is automatically compiled into a column, which does not match the actual number of columns

{
  "timestamp": 1481377345590,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "org.springframework.jdbc.IncorrectResultSetColumnCountException",
  "message": "Incorrect column count: expected 1, actual 4",
  "path": "/venus/user/getUserList"
}
5.2 Bulk Insert

method 1:

@Override
@Transactional
public Integer batchInsertUsers(List<UserDto> listUser) {
    String sql = "insert vns_user(u_code,u_name,u_age) values(?,?,?)";
    jdbcTemplate.batchUpdate(sql,new BatchPreparedStatementSetter()
    {
        public void setValues(PreparedStatement ps, int i)throws SQLException
        {
            String code = listUser.get(i).getuCode();
            String name=listUser.get(i).getuName();
            int age=listUser.get(i).getuAge();
            ps.setString(1,code);
            ps.setString(2, name);
            ps.setInt(3, age);
        }
        public int getBatchSize()
        {
            return listUser.size();
        }
    });
    return 0;
}

Method 2:

@Override
@Transactional
public Integer batchInsertUsers(List<UserDto> listUser) {
    String sql = "insert vns_user(u_code,u_name,u_age) values(?,?,?)";
    jdbcTemplate.batchUpdate(sql,setParameters(listUser));
    return 0;
}

/**
 * 设置参预置数
 * @param listUser
 * @return
 */
private List<Object[]> setParameters(List<UserDto> listUser){
    List<Object[]> parameters = new ArrayList<Object[]>();
    for (UserDto u : listUser) {
        parameters.add(new Object[] { u.getuCode(),u.getuName(),u.getuAge()});
    }
    return parameters;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326445005&siteId=291194637