jdbcTemplate的使用
准备: 已存在的数据表
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=UTF-8&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
@Data
public class Book {
private int id;
private String name;
private String type;
private String description;
}
@SpringBootTest
class SpringbootJdbctemplateApplicationTests {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
void testQuery(){
String sql="select * from book ";
RowMapper<Book> rm=new RowMapper<Book>() {
@Override
public Book mapRow(ResultSet rs, int rowNum) throws SQLException {
Book book=new Book();
book.setId(rs.getInt("id"));
book.setName(rs.getString("name"));
book.setType(rs.getString("type"));
book.setDescription(rs.getString("description"));
return book;
}
};
List<Book> books=jdbcTemplate.query(sql,rm);
System.out.println(books);
}
}
执行结果可以看到查到的List集合
5. 编写测试(保存操作),并执行
@Test
void testUpdate(){
String sql="insert into book (name,type,description) VALUES ('hello','测试','测试内容')";
int i=jdbcTemplate.update(sql);
System.out.println(i);
}
执行结果可以看到影响的记录行为1
从上面的例子,我们只是配置了数据源,并没有声明数据源,但是运行日志可以看到系统默认了Hikari数据源
当然我们也可以使用其他数据源。
Springboot提供了3种内嵌数据源
通用数据源配置:
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=UTF-8&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/mydb?characterEncoding=UTF-8&useSSL=false #这一行不能声明在hikari的层级之下
hikari:
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver