本文來自於千鋒教育在阿里雲開發者社區學習中心上線課程《SpringBoot實戰教程》,主講人楊紅豔,點擊查看視頻內容。
SpringBoot整合JdbcTemplate
我們需要把依賴放入工程當中:
<!-- springboot整合jdbctemplate -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- mysql的依賴 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
我們使用數據庫db1,users表:
需要先生成Users的實體類;
之後創建Dao層:
UserDao:
@Repository
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void addUser(User user) {
jdbcTemplate.update("insert into users(name,password,email,birthday) values(?,?,?,?)", new Object[ ]{user.getName(), user.getPassword(), user.getEmail(), user.getBirthday()});
}
}
創建Service層:
UserService:
@Service
public class UserService {
@Autowired
private UserDao userDao;
public void saveUser(User user) {
userDao.addUser(user);
}
}
創建Controller層:
UserController:
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/savaUser")
@ResponseBody
public String save() {
Users user = new Users();
user.setName("王喜");
user.setPassword("6666");
user.setEmail("[email protected]");
user.setBirthday(new Date());
userService.savaUser(user);
return "success";
}
}
在啟動類中添加所有需要掃描的包
@SpringBootApplication(scanBasePackages={"com.qianfeng.dao","com.qianfeng.service","com.qianfeng.controller"})
在全局配置文件中添加連接數據庫的信息:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/db1
執行結果: