【发布时间】:2019-01-12 11:35:36
【问题描述】:
我正在学习结合 Spring Boot 和 jdbcTemplate 进行一些基本的 crud 操作,并试图更好地了解我应该选择哪种更新方法。
我了解以下两种类方法(改编自this post)会将相同的记录写入数据库。
示例 1:
public class InsertDemo {
private static final String sql =
"INSERT INTO records (title, " +
" release_date, " +
" artist_id, " +
" label_id, " +
" created) " +
"VALUES (?, ?, ?, ?, ?)";
private DataSource dataSource;
public InsertDemo(DataSource dataSource) {
this.dataSource = dataSource;
}
public void saveRecord(String title, Date releaseDate,
Integer artistId, Integer labelId) {
JdbcTemplate template = new JdbcTemplate(this.dataSource);
Object[] params = new Object[] {
title, releaseDate, artistId, labelId, new Date()
};
int[] types = new int[] {
Types.VARCHAR,
Types.DATE,
Types.INTEGER,
Types.INTEGER,
Types.DATE
};
int row = template.update(sql, params, types);
System.out.println(row + " row inserted.");
}
示例 2:
public class InsertDemo {
private static final String sql =
"INSERT INTO records (title, " +
" release_date, " +
" artist_id, " +
" label_id, " +
" created) " +
"VALUES (?, ?, ?, ?, ?)";
private DataSource dataSource;
public InsertDemo(DataSource dataSource) {
this.dataSource = dataSource;
}
public void saveRecord(String title, Date releaseDate,
Integer artistId, Integer labelId) {
JdbcTemplate template = new JdbcTemplate(this.dataSource);
Object[] params = new Object[] {
title, releaseDate, artistId, labelId, new Date()
};
int row = template.update(sql, params);
System.out.println(row + " row inserted.");
}
但我不清楚为什么我会/应该使用第一个指定参数类型的参数。我已经阅读了the javadoc,但我仍然不确定为什么需要指定类型。我错过了什么?
【问题讨论】:
标签: java spring-boot jdbctemplate