一:引入jdbcTemplate依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
如果在JPA已经加入的话,则可以不用引入以上的配置。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
编写DAO
直接使用就可以了
@Resource
private JdbcTemplate jdbcTemplate;
package com.mt.dog.dao; import java.util.List; import javax.annotation.Resource; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import com.mt.dog.entity.Dog; @Repository public class DogDao { @Resource private JdbcTemplate jdbcTemplate; public Dog getDogById(Long id) { String sql = "select * from dog where id=? "; RowMapper<Dog> rowMapper = new BeanPropertyRowMapper<>(Dog.class); List<Dog> dogs = jdbcTemplate.query(sql, new Object[] { id }, rowMapper); return dogs.get(0); } }
一个走投无路的庄稼汉