问题描述
我已经有一个 UserRowMapper
,它实现RowMapper<用户>
。
如何做到这一点?
我试过了:
pre $ List rows = getJdbcTemplate()。queryforList(select * from users); (Map row:rows){
}
$ b $
b
但不知道如何使用我的UserRowMapper填充User对象并将其插入到我的List用户列表中。
顺便说一句,这是最好的通用列表我应该使用:
列表<用户> users = new ArrayList< User>();
?
使用,并且可以为?
占位符传递可变数量的值作为最后一个参数: / p>
public List< User> findById(int userId)
{
return getJdbcTemplate()。query(
SELECT * FROM users WHERE user_id =?,
new UserRowMapper(),
userId
);
}
或者类似:
public List< User> findByManyParams(int param1,int param2,String param3)
{
return getJdbcTemplate()。query(
SELECT * FROM users WHERE foo =?AND bar =?AND foobar =?,
new UserRowMapper(),
param1,
param2,
param3
);
query()
方法实际上被重载了很多次,所以你通常可以在任何给定的情况下至少找到一种适合你需要的风味。
In my UserDao I want to return a list of users.
I already have a UserRowMapper
that implements RowMapper<User>
.
How can I do this?
I tried:
List rows = getJdbcTemplate().queryforList("select * from users");
for(Map row : rows) {
}
But wasn't sure how to use my UserRowMapper to populate a User object and insert it into my list of users List.
BTW, is this the best generic list I shoudl be using:
List<User> users = new ArrayList<User>();
?
Use JdbcTemplate.query(String sql, RowMapper<T> rowMapper, Object... args)
, and you can pass in a variable number of values for the ?
placeholders as the last argument(s):
public List<User> findById(int userId)
{
return getJdbcTemplate().query(
"SELECT * FROM users WHERE user_id=?",
new UserRowMapper(),
userId
);
}
Or something like:
public List<User> findByManyParams(int param1, int param2, String param3)
{
return getJdbcTemplate().query(
"SELECT * FROM users WHERE foo=? AND bar=? AND foobar=?",
new UserRowMapper(),
param1,
param2,
param3
);
}
The query()
method is actually overloaded many times over, so you can usually find at least one flavor that works for what you need in any given situation.
这篇关于返回一个列表,我已经有了一个rowmapper实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!