java - 在 jdbcTemplate.update(String sql,Object[] args,int[] argTypes) 和 jdbcTemplate.update(String sql,Object[] args) 之间进行选择
问题描述
我正在学习结合 Spring Boot 和 jdbcTemplate 进行一些基本的 crud 操作,并试图更好地了解我应该选择哪种更新方法。
我知道以下两种类方法(改编自这篇文章)会将相同的记录写入数据库。
示例 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.");
}
但我不清楚为什么我会/应该使用第一个指定参数类型的。我已经阅读了 javadoc,但我仍然不确定为什么需要指定类型。我错过了什么?
解决方案
设置参数类型为底层 SQL 语句提供了正确性和优化(轻微)。(JdbcTemplate
内部构建 aPreparedStatement
并使用提供/派生的类型为其设置值)。
在您的示例中,如果您未指定Types
数组,则它们将被设置为SqlTypeValue.TYPE_UNKOWN
最终被猜测或解析为;
if (sqlType == SqlTypeValue.TYPE_UNKNOWN || sqlType == Types.OTHER) {
if (isStringValue(inValue.getClass())) {
ps.setString(paramIndex, inValue.toString());
}
else if (isDateValue(inValue.getClass())) {
ps.setTimestamp(paramIndex, new java.sql.Timestamp(((java.util.Date) inValue).getTime()));
}
else if (inValue instanceof Calendar) {
Calendar cal = (Calendar) inValue;
ps.setTimestamp(paramIndex, new java.sql.Timestamp(cal.getTime().getTime()), cal);
}
else {
// Fall back to generic setObject call without SQL type specified.
ps.setObject(paramIndex, inValue);
}
}
看一下org.springframework.jdbc.core.StatementCreatorUtils#setValue
因此,设置 arg 类型是一个好习惯。
推荐阅读
- amazon-web-services - GeoSpark Zeppelin 氦气插件
- ionic-framework - 离子框架中的Playstore问题
- sql - 在一行中查找并保留唯一值
- plugins - CKeditor5 - 插件 - 小部件 - 状态
- javascript - 如何在点击时用 JavaScript 替换 HTML 文档中两个常量之间的变量?
- sql - 我可以在一个查询中选择两个表吗?
- node.js - 如何在 Node js 中使用 Google Hangout 聊天 space.message.get 获取消息
- typo3 - 具有多个选项的表单元素的翻译
- android - 用于在 Android 6.0 上返回 null 的 firebase 读取数据的 addValueEventListener
- docker - 生产环境中 Ubuntu 上的最小 Kubernetes 集群