Spring Boot 使用JDBCTemplate
1、加入相關依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency>
2、 User實體類
import lombok.Data;
@Data
public class User {
private Long id;
private String name;
private int age;
private int sex;
}
3、Dao接口和實作類
public interface UserDao { User get(Long id); } ------------------------------------------------------------------------------------------- @Repository public class UserDaoImpl implements UserDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public User get(Long id) { return jdbcTemplate.queryForObject("select * from t_user where id = ?",new Object[]{id},new BeanPropertyRowMapper<>(User.class)); } }
注意Dao實作類使用@Respository注解,表明為持久層;
注入JdbcTemplate,至于JdbcTemplate具體使用方法,可自行研究,本博文主要簡單介紹如何使用
4 、Service及實作類
public interface UserService { User get(Long id); } ------------------------------------------------------------------------------------------- @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public User get(Long id) { return userDao.get(id); } }
5、Controller
@RestController public class UserController { @Autowired private UserService userService; @GetMapping(value = "/getUser") public String getUserInfo(){ return userService.get(1L).toString(); } }
浏覽器通路:localhost:8080/getUser