在項目中可能會遇到,項目架構是hibernate,但某些查詢仍是習慣用sql語句來作,或者某些查詢用sql語句更加簡單靈活。這時候咱們能夠注入jdbcTemplate。spring
1.在非springboot項目中jdbctemplate的配置及注入
配置:在spring-config.xml中註冊bean,注意在註冊bean時須要將datasource添加進入sql
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean>
注入:在使用jdbctemplate的地方springboot
@Autowired private JdbcTemplate jdbcTemplate;
2.在springboot項目中
添加jdbc的座標。配置文件中正常配置數據源相關內容,以下:
<dependency>架構
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
注入:app
@Autowired private JdbcTemplate jdbcTemplate;
3.查詢
a.獲取一個對象集合,經過BeanPropertyRowMapper將sql獲取的結果映射到對應的對象中spring-boot
String sql="select app_id appId,count from table"; List<TracePointTypeDTO> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(TracePointTypeDTO.class)); 若須要有參數傳入 String sql="select app_id appId,count from table where app_id=?"; List<TracePointTypeDTO> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(TracePointTypeDTO.class),new Object[]{appId}); b.獲取String對象的集合 String timeSql="select update_time from apps_exchange_rate group by update_time order by update_time desc;"; List<String> strings =jdbcTemplate.query(timeSql, new RowMapper<String>() { public String mapRow(ResultSet rs, int rowNum) throws SQLException { return rs.getString(1); } });