MVC三層架構
MVC三層架構
-
通常會拆成三層
- Controller -->負責接收前端數據
- Service --> 業務邏輯
- DAO --> 與資料庫溝通
-
通常還會做成interface以利解耦 另外使用一個impl來實作這個interface
-
DAO
public interface StudentDao {
Student getById(Integer studentId);
List<Student> getAll();
String deleteById(Integer studentId);
String add(Student student);
String addBatch(List<Student> studentList);
@Component //使用component註解使其成為bean
public class StudentDaoImpl implements StudentDao {
@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@Override
public Student getById(Integer studentId) {
String sql = "SELECT id, name FROM student WHERE id= :studentId";
Map<String, Object> map = new HashMap<>();
map.put("studentId", studentId);
List<Student> students = namedParameterJdbcTemplate.query(sql, map,new StudentRowMapper());
return students.isEmpty() ? null : students.get(0);
}
//...以下各種實作
- Service
public interface StudentService {
Student getById(Integer studentId);
List<Student> getAll();
String deleteById(Integer studentId);
String add(Student student);
String addBatch(List<Student> studentList);
}//基本上與dao一樣
@Component
public class StudentServiceImpl implements StudentService{
@Autowired //使用autowired使用dao的bean
private StudentDao studentDao;
@Override
public Student getById(Integer studentId) {
return studentDao.getById(studentId);
}
@Override
public List<Student> getAll() {
return studentDao.getAll();
}
//......
- Controller
@RestController
public class StudentController {
@Autowired
//同樣使用autowired使用bean
private StudentService studentService;
@PostMapping("/students")
public String insert(@RequestBody Student student) {
return studentService.add(student);
}
@PostMapping("/students/batch")
public String insertBatch(@RequestBody List<Student> studentList) {
return studentService.addBatch(studentList);
}
//......