开门见山吧,首先我们在MySQL中创建数据库:
CREATE DATABASE IF NOT EXISTS springboot_project DEFAULT CHARSET utf8;
然后在springboot_project数据库中创建temp表:
CREATE TABLE `temp` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) DEFAULT NULL,
`code` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
首先我们在pom.xml中引入jdbc的依赖:
org.springframework.boot
spring-boot-starter-jdbc
然后引入mysql连接和druid连接池:
mysql
mysql-connector-java
runtime
com.alibaba
druid
1.0.29
当然我们最后需要Controller层做个简单的测试,所以把web依赖也引入进来:
org.springframework.boot
spring-boot-starter-web
在application-dev.properties文件配置mysql的驱动类、数据库连接地址、账号和密码:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot_project
spring.datasource.username=root
spring.datasource.password=Anbang713
public class Temp {
private Integer id;
private String name;
private String code;
// 这里省略getter和setter
}
public interface TempDao {
int save(Temp entity) throws Exception;
Temp get(Integer id);
}
@Repository
public class TempDaoImpl implements TempDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public int save(Temp entity) throws Exception {
if (entity.getId() != null) {
return jdbcTemplate.update("update temp set name = ?, code = ? where id = ?",
entity.getName(), entity.getCode(), entity.getId());
}
return jdbcTemplate.update("insert into temp(name, code) values(?,?)", entity.getName(),
entity.getCode());
}
@Override
public Temp get(Integer id) {
List result = jdbcTemplate.query("select * from temp where id = ?", new Object[] {
id }, new BeanPropertyRowMapper(Temp.class));
if (result == null || result.isEmpty()) {
return null;
}
return result.get(0);
}
}
public interface TempService {
int save(Temp entity) throws Exception;
Temp get(Integer id);
}
@Service
public class TempServiceImpl implements TempService {
@Autowired
private TempDao tempDao;
@Override
public int save(Temp entity) throws Exception {
return tempDao.save(entity);
}
@Override
public Temp get(Integer id) {
return tempDao.get(id);
}
}
@RestController
@RequestMapping("/temp/*")
public class TempController {
@Autowired
private TempService tempService;
@RequestMapping(value = "{id}", method = RequestMethod.GET)
public Temp get(@PathVariable("id") Integer id) {
return tempService.get(id);
}
@RequestMapping(value = "save", method = RequestMethod.POST)
public Integer save(@RequestBody Temp entity) throws Exception {
return tempService.save(entity);
}
}
至此,我们所有的编码都已经实现了,我们的整个代码结构看起来是这样的:
首先我们通过save接口新建一条数据:
然后我们通过get接口取出id为1的数据:
我们再通过save接口修改id为1的name字段,将zhangsan修改为lisi:
源代码地址:https://gitee.com/chengab/SpringBoot/tree/master/springboot/src/main/java/com/study/springboot/jdbctemplates
参考博客:SpringBoot非官方教程 | 第三篇:SpringBoot用JdbcTemplates访问Mysql