springboot引入jdbcTemplate
1、pom
org.springframework.boot
spring-boot-starter-jdbc
2、数据库配置
spring
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/demo_test?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=UTF8
password: root
username: root
3、使用
@Autowired
private JdbcTemplate jdbcTemplate;
public List testJdbcTemplate(Integer id) {
// 不用参数,返回list实体类
String sql = " select * from parent ";
List query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Parent.class));
// 有两个参数 (方法1)
String sqlA = "select * from parent where relation = ? and child = ? ";
Object[] params = {"父","1"};
List listA = jdbcTemplate.query(sqlA,params, new BeanPropertyRowMapper<>(Parent.class));
// 有两个参数 (方法2)
List listB = jdbcTemplate.query(sqlA,new BeanPropertyRowMapper<>(Parent.class),"父","1");
// 有两个参数 (方法3)
ArrayList paramList = new ArrayList<>();
paramList.add("父");
paramList.add("1");
Object[] args = paramList.toArray(); // list转数组
List listC = jdbcTemplate.query(sqlA, args,new BeanPropertyRowMapper<>(Parent.class));
// 返回map
List
jdbcTemplate多数据源配置
在我另一遍文章 druid配置里有写配置
使用:
@Autowired
@Qualifier("jdbcTemplate2")
private JdbcTemplate jdbcTemplate2;