使用JdbcTemplate查询数据库的例子
配置等可以看前一篇文章: Spring JdbcTemplate实例
创建数据库
可以使用下面的SQL
create table A(
`id` INT (255) not null,
primary key (`id`)
);
创建实体类
新建一个AEntity
类用于映射表A的一行:
@Component
public class AEntity {private int id;public int getId() {return id;}public void setId(int id) {this.id = id;}}
接写来的App
类将演示从数据库里查询数据。
查询一行
关键代码:template.queryForObject(String sql, RowMapper<T> rowMapper)
。
@Component("app")
public class App
{ @Resourceprivate JdbcTemplate jdbcTempalte;public static void main( String[] args ){ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");App app = (App) context.getBean("app");JdbcTemplate template = app.getJdbcTempalte();AEntity aEntity = (AEntity) template.queryForObject("select * from a where id = 1 ", new RowMapper<AEntity>(){@Overridepublic AEntity mapRow(ResultSet rs, int rowNum) throws SQLException {AEntity aEntity = new AEntity();aEntity.setId( rs.getInt("id") );return aEntity;}} );System.out.println(aEntity.getId());}public JdbcTemplate getJdbcTempalte() {return jdbcTempalte;}public void setJdbcTempalte(JdbcTemplate jdbcTempalte) {this.jdbcTempalte = jdbcTempalte;}}
查询集合
@Component("app")
public class App
{ @Resourceprivate JdbcTemplate jdbcTempalte;public static void main( String[] args ){ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");App app = (App) context.getBean("app");JdbcTemplate template = app.getJdbcTempalte();List<Long> list = template.queryForList("select * from a limit 0,15 ",Long.class);for(Long id : list){System.out.println(id);}}public JdbcTemplate getJdbcTempalte() {return jdbcTempalte;}public void setJdbcTempalte(JdbcTemplate jdbcTempalte) {this.jdbcTempalte = jdbcTempalte;}}