In a project, you may encounter that the project architecture is hibernate, but some queries are still used to sql statements, or some queries are more simple and flexible with sql statements. At this point we can inject jdbcTemplate.
1. Configuration and injection of jdbctemplate in non-spring boot projects
Configuration: Register beans in spring-config.xml. Note that when registering beans, you need to add data source to it.
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean>
Injection: Where jdbctemplate is used
@Autowired private JdbcTemplate jdbcTemplate;
2. In the spring boot project
Add jdbc coordinates. The normal configuration of data sources in the configuration file is as follows:
<dependency>
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
Injection:
@Autowired private JdbcTemplate jdbcTemplate;
3. query
A. Get a collection of objects and map the results obtained by sql to the corresponding objects through BeanProperty RowMapper
String sql="select app_id appId,count from table"; List<TracePointTypeDTO> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(TracePointTypeDTO.class)); //If parameter input is required 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.Obtain String Collection of objects 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); } });