JdbcTemplate中向in语句传参
spring jdbc包提供了JdbcTemplate和它的两个兄弟SimpleJdbcTemplate和NamedParameterJdbcTemplate,我们先从JdbcTemplate入手,
引入问题,领略一下类NamedParameterJdbcTemplate在处理where中包含in时的便利和优雅。
首先创建实体类Employee:
public class Employee {
private Long id;
private String name;
private String dept;
// omit toString, getters and setters
}
使用JdbcTemplate访问一批数据
比较熟悉的使用方法如下:
public List<Employee> queryByFundid(int fundId) {
String sql = "select * from employee where id = ?";
Map<String, Object> args = new HashMap<>();
args.put("id", 32);
return jdbcTemplate.queryForList(sql, args , Employee.class );
}
但是,当查询多个部门,也就是使用in的时候,这种方法就不好用了,只支持Integer.class String.class 这种单数据类型的入参。如果用List匹配问号,你会发现出现这种的SQL:
select * from employee where id in ([1,32])
执行时一定会报错。解决方案——直接在Java拼凑入参,如:
String ids = "3,32";
String sql = "select * from employee where id in (" + ids +")";
如果入参是字符串,要用两个''号引起来,这样跟数据库查询方式相同。示例中的入参是int类型,就没有使用单引号。但是,推荐使用NamedParameterJdbcTemplate类,然后通过: ids方式进行参数的匹配。
使用NamedParameterJdbcTemplate访问一批数据
public List<Employee> queryByFundid(int fundId) {
String sql = "select * from employee where id in (:ids) and dept = :dept";
Map<String, Object> args = new HashMap<>();
args.put("dept", "Tech");
List<Integer> ids = new ArrayList<>();
ids.add(3);
ids.add(32);
args.put("ids", ids);
NamedParameterJdbcTemplate givenParamJdbcTemp = new NamedParameterJdbcTemplate(jdbcTemplate);
List<Employee> data = givenParamJdbcTemp.queryForList(sql, args, Employee.class);
return data;
}
如果运行以上程序,会采坑,抛出异常:org.springframework.jdbc.IncorrectResultSetColumnCountException: Incorrect column count: expected 1, actual 3。
抛出此异常的原因是方法queryForList 不支持多列,但是,API(spring-jdbc-4.3.17.RELEASE.jar)并未说明。请看queryForList 在JdbcTemplate的实现:
public <T> List<T> queryForList(String sql, SqlParameterSource paramSource, Class<T> elementType)
throws DataAccessException {
return query(sql, paramSource, new SingleColumnRowMapper<T>(elementType));
} /**
* Create a new {@code SingleColumnRowMapper}.
* <p>Consider using the {@link #newInstance} factory method instead,
* which allows for specifying the required type once only.
* @param requiredType the type that each result object is expected to match
*/
public SingleColumnRowMapper(Class<T> requiredType) {
setRequiredType(requiredType);
}
查询API发现,需要换一种思路,代码如下:
public List<Employee> queryByFundid(int fundId) {
String sql = select * from employee where id in (:ids) and dept = :dept
Map<String, Object> args = new HashMap<>();
args.put("dept", "Tech");
List<Integer> ids = new ArrayList<>();
ids.add(3);
ids.add(32);
args.put("ids", ids);
NamedParameterJdbcTemplate givenParamJdbcTemp = new NamedParameterJdbcTemplate(jdbcTemplate);
List<Employee> data = givenParamJdbcTemp.jdbc.query(sql, args, new RowMapper<Employee>() {
@Override
public Employee mapRow(ResultSet rs, int index) throws SQLException {
Employee emp = new Employee();
emp.setId(rs.getLong("id"));
emp.setName(rs.getString("name"));
emp.setDept(rs.getString("dept"));
return emp;
}
});
return data;
}
欢迎拍砖。
JdbcTemplate中向in语句传参的更多相关文章
- js中使用进行字符串传参
在js中拼接html标签传参时,如果方法参数是字符串需要加上引号,这里需要进行字符转义 <a href='javascript:addMenuUI("+"\"&qu ...
- python中导入一个需要传参的模块
最近跑实验,遇到了一个问题:由于实验数据集比较多,每次跑完一个数据集就需要手动更改文件路径,再将文件传到服务器,再运行实验,这样的话效率很低,必须要专门看着这个实验,啥时候跑完就手动修改运行下一个实验 ...
- requests中get和post传参
get请求 get(url, params=None, **kwargs) requests实现get请求传参的两种方式 方式一: import requests url = 'http://www. ...
- vue中组件间的传参
1.父传子 父组件准备一个数据,通过自定义属性给子组件赋值,进行传递 在子组件中通过 props 属性来接收参数 <body> <div id="app"> ...
- 使用python读取配置文件并从mysql数据库中获取数据进行传参(基于Httprunner)
最近在使用httprunner进行接口测试,在传参时,用到了三种方法:(1)从csv文件中获取:(2)在config中声名然后进行引用:(3)从函数中获取.在测试过程中,往往有些参数是需要从数据库中获 ...
- mybatis-sql语句传参
MyBatis中的映射语句有一个parameterType属性来制定输入参数的类型.但是parameterType属性只可以写一个参数,所以如果我们想给映射语句传入多个参数的话,我们可以将所有的输入参 ...
- vue-router中query和params传参(接收参数)以及$router、$route的区别
query传参: this.$router.push({ path:'/...' query:{ id:id } }) 接收参数:this.$route.query.id params传值: 传参: ...
- vue中this.$router.push() 传参
1 params 传参 注意⚠️:patams传参 ,路径不能使用path 只能使用name,不然获取不到传的数据 this.$router.push({name: 'dispatch', para ...
- ZZW_shell脚本中的调用MYSQL传参及注意的问题
[oracle@ip9140 db_pcc]$ cat zzw_cc.sh #!/bin/bash z_user='pcc_csuser22'z_pass='pcc_csuser22'z_db='db ...
随机推荐
- EntityFramework 多数据库链接,MySql,SqlServer,Oracel等
环境:EntityFramework5.0,MySql5.6,MSSQL2012 EF是强大的ORM工具,真正意义上的多数据库链接指的是不同类型的数据库,以及同种类型的数据库多个库,EF很好的支持这一 ...
- java.lang.String.regionMatches方法使用
regionMatches(boolean ignoreCase,int toffset,String other,int ooffset,int len): regionMatches(int to ...
- 大数据基础篇----jvm的知识点归纳-5个区和垃圾回收机制
一直对jvm看了又忘,忘了又看的.今天做一个笔记整理存放在这里. 我们先看一下JVM的内存模型图: 上面有5个区,这5个区干嘛用的呢? 我们想象一个场景: 我们有一个class文件,里面有很多的类的定 ...
- RedisLive监控工具 windows部署笔记
1. Python2.7环境安装 Path环境变量中添加 2.下载安装 VC Compiler for Python 地址: http://www.microsoft.com/en-us/dow ...
- Spring 3 Java Based Configuration with @Value
Springsource has released the Javaconfig Framework as a core component of Spring 3.0. There is a tre ...
- websphere 删除文件
META-INF 文件夹下加入ibm-partialapp-delete.props即可 里面添加路径 如WEB-INF/xxx/xxx.xxx
- (转) at&T语法格式 与 at&T - intel格式对比
原地址 示例: movl (%ebp), %eax, 等同于Intel格式中的 ] ,AT&T中,源操作数在左,目的操作数在右.“l”是Longword,相当于Intel格式中的dword p ...
- [PHP] 01 - Hypertext Preprocessor
超级文本预处理语言:http://php.net/ 集成的服务器组件,它已经包含了 PHP.Apache.Mysql 等服务 PHP 7 https://www.tutorialspoint. com ...
- ASP.NET MVC 4 (十一) Bundles和显示模式
Bundles用于打包CSS和javascript脚本文件,优化对它们的组织管理.显示模式则允许我们为不同的设备显示不同的视图. 默认脚本库 在VS创建一个MVC工程,VS会为我们在scripts目录 ...
- mac环境变量
环境: 当前已经有 .bash_profile文件了 打开.bash_profile: open -e .bash_proile open -e .bash_profile 查看node安装路径: w ...