<a>
링크 추가 <div class="row mb-3">
<div class="col-12">
<div class="text-end">
<a href="create" class="btn btn-primary">신규 부서</a>
</div>
</div>
</div>
@GetMapping("/create")
public String form(Model model) {
return "dept/form";
}
<form class="border bg-light p-3" method="post" action="create">
<div class="form-group mb-3">
<label class="form-label">부서명</label>
<input type="text" class="form-control" name="name" />
</div>
<div class="form-group mb-3">
<label class="form-label">부서연락처</label>
<input type="text" class="form-control" name="tel" />
</div>
<div class="form-group mb-3">
<label class="form-label">팩스번호</label>
<input type="text" class="form-control" name="fax" />
</div>
<div class="text-end">
<button type="submit" class="btn btn-primary">등록</button>
</div>
</form>
@Getter
@Setter
@ToString
public class DeptCreateForm {
// form클래스에는 입력화면에 있는 변수만 있어야 함. -> no는 없어야 함
private String name;
private String tel;
private String fax;
}
/* 날짜 형식은 아래처럼 정의
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date hireDate;
*/
@PostMapping("/create")
public String create(DeptCreateForm deptCreateForm) {
hrService.createDept(deptCreateForm);
return "redirect:list";
}
public void createDept(DeptCreateForm form) {
Dept dept = Dept.builder()
.name(form.getName())
.tel(form.getTel())
.fax(form.getFax())
.build();
deptMapper.insertDept(dept);
}
void insertDept(Dept dept);
<insert id="insertDept" parameterType="com.sample.vo.Dept">
insert into shop_depts
values
(depts_seq.nextval, #{name}, #{tel}, #{fax})
</insert>
- Builder의 메서드 체이닝 방법
(Service의 코드가 길어짐)
@Getter
@Setter
@ToString
public class EmpCreateForm {
private String name;
private String tel;
private String email;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date hireDate;
private int salary;
private int deptNo;
}
public void createEmp(EmpCreateForm form) {
// 등록 폼에서 부서번호 조회하기 위해 필요
Dept dept = Dept.builder()
.no(form.getDeptNo())
.build();
// 빌더가 모든 생성자를 알아서 만들어줌
Employee emp = Employee.builder()
.name(form.getName())
.tel(form.getTel())
.email(form.getEmail())
.salary(form.getSalary())
.hireDate(form.getHireDate())
.dept(dept)
.build();
empMapper.insertEmp(emp);
}
2. Form클래스에 정의한 메서드 호출 방법
(Service 코드 단 한 줄)
@Getter
@Setter
@ToString
public class EmpCreateForm {
private String name;
private String tel;
private String email;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date hireDate;
private int salary;
private int deptNo;
// 객체를 set해주는 메서드 정의
public Employee toEmp() {
Employee emp = new Employee();
emp.setName(name);
emp.setTel(tel);
emp.setEmail(email);
emp.setSalary(salary);
emp.setHireDate(hireDate);
Dept dept = new Dept();
dept.setNo(deptNo);
emp.setDept(dept);
return emp;
}
}
public void createEmp(EmpCreateForm form) {
// Form클래스 메서드 호출
Employee emp = form.toEmp();
empMapper.insertEmp(emp);
}