最近愈发的发现spring的功能是如此强大,感觉spring好像把java开发过程中的很多事情都替代了,一旦不理解原理,流程等等,就真的把程序员变成码农了。好吧,在使用jdbcTemplate.query进行查询过程中始终查不到值,在查看说明文档帮助下,最终了解JdbcTemplate.query的使用方法。
1.最简单的用法,查询统计行数,返回int,
[java]
int rowCount = this.jdbcTemplate.queryForObject("select count(*) from t_actor", Integer.class);</pre>
[/java]
2.使用占位符参数查询
int countOfActorsNamedJoe = this.jdbcTemplate.queryForObject( "select count(*) from t_actor where first_name = ?", Integer.class, "Joe");
3.查询返回String
String lastName = this.jdbcTemplate.queryForObject( "select last_name from t_actor where id = ?", new Object[]{1212L}, String.class);
4.查询返回一个对象
Actor actor = this.jdbcTemplate.queryForObject( "select first_name, last_name from t_actor where id = ?", new Object[]{1212L}, new RowMapper<Actor>() { public Actor mapRow(ResultSet rs, int rowNum) throws SQLException { Actor actor = new Actor(); actor.setFirstName(rs.getString("first_name")); actor.setLastName(rs.getString("last_name")); return actor; } });
5.查询返回一个list
List<Actor> actors = this.jdbcTemplate.query( "select first_name, last_name from t_actor", new RowMapper<Actor>() { public Actor mapRow(ResultSet rs, int rowNum) throws SQLException { Actor actor = new Actor(); actor.setFirstName(rs.getString("first_name")); actor.setLastName(rs.getString("last_name")); return actor; } });
上述代码可以精简为如下:
public List<Actor> findAllActors() { return this.jdbcTemplate.query( "select first_name, last_name from t_actor", new ActorMapper()); } private static final class ActorMapper implements RowMapper<Actor> { public Actor mapRow(ResultSet rs, int rowNum) throws SQLException { Actor actor = new Actor(); actor.setFirstName(rs.getString("first_name")); actor.setLastName(rs.getString("last_name")); return actor; } }
jdbcTemplate/namedJdbcTemplate在不用持久层框架的时候,的确是一个很好的jdbc的框架,用起来特别方便,还不用维护连接池,底层采用common-dbcp来实现的jdbc连接,稳定性是几大框架中最好的一个。
spring JdbcTemplate.query使用简介