正文
springboot学习(七) 使用JdbcTemplate
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
1、对内嵌数据库的支持
内嵌数据库通常用于开发和测试环境,不推荐用于生产环境。Spring Boot提供自动配置的嵌入式数据库有H2、HSQL、Derby,你不需要提供任何连接配置就能使用。
例子:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> <dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
2、连接生产数据库(Mysql)
导入数据库依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
然后在application.properties配置文件中添加mysql配置:
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
3、使用JdbcTemplate操作数据库
首先在数据库中创建用户表USER,并添加字段name和age。
接口类:
public interface UserService { /**
* 新增一个用户
* @param name
* @param age
*/
void create(String name, Integer age); /**
* 根据name删除一个用户高
* @param name
*/
void deleteByName(String name); /**
* 获取用户总量
*/
Integer getAllUsers();
}
实现类:
@Service
public class UserServiceImpl implements UserService { @Autowired
private JdbcTemplate jdbcTemplate; @Override
public void create(String name, Integer age) {
jdbcTemplate.update("insert into USER(NAME, AGE) values(?, ?)", name, age);
} @Override
public void deleteByName(String name) {
jdbcTemplate.update("delete from USER where NAME = ?", name);
} @Override
public Integer getAllUsers() {
return jdbcTemplate.queryForObject("select count(1) from USER", Integer.class);
}
}
测试类:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class JdbcTest { @Autowired
private UserService userService; @Test
public void test() {
userService.create("a1", 11); System.out.println("----"); System.out.println(userService.getAllUsers());
}
}