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数据库查询实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安卓阵营其它品牌出货量都下滑唯独荣耀增长
- 下一篇: 国内车主赚翻!长城欧拉好猫将在英国上市