spring JdbcTemplate数据库查询实例
生活随笔
收集整理的这篇文章主要介绍了
spring JdbcTemplate数据库查询实例
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
使用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;}}总结
以上是生活随笔为你收集整理的spring JdbcTemplate数据库查询实例的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 安卓阵营其它品牌出货量都下滑唯独荣耀增长
- 下一篇: mysql获取当前时间毫秒_MySQL性