一、pom文件引入依赖(注:springboot的parent版本必须是1.5以上的)
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
二、在resources下的application.properties加上数据库的配置(这里用mysql,其他数据库同理)
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
三、service实现类编写具体数据库操作
@Service
public class UserServiceImpl implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void createJdbcUser() {
jdbcTemplate.update("insert into chinese values(?,?)", new Object[]{2,23});
}
}
主函数类加上service的扫包:@ComponentScan(basePackages={"com.wcj.controller","com.wcj.service"})
四、controller如下:
@RestController
public class JdbctemplateController {
@Autowired
private UserService userService;
@RequestMapping("/jdbctemplateTest")
public String jdbctemplateTest() {
userService.createJdbcUser();
return "testtest";
}
}
五、运行如图: