250x250
Notice
Recent Posts
Recent Comments
Link
관심쟁이 영호
[#5] JPA를 이용한 DB insert 본문
반응형
JPA를 이용한 DB insert
이번에는 JPA를 이용하여 DB에 회원가입 정보를 insert 해보자.
다루게될 목차는 다음과 같다.
- Sign Up 프론트 구현
- Sign Up 컨트롤러 구현
- User Repository 구현
- Sign Up 서비스 구현
Sign Up 프론트 구현
프론트 디자인은 신경쓰지 않고, 아주 간단하게 하였다.
먼저 구현된 화면은 다음과 같다.
signup.html
다음은 코드이다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>회원가입</title>
</head>
<body>
회원가입입니다.
<form action="/signup" method="post">
아이디 : <input type="text" name="id"/><br>
비밀번호: <input type="text" name="password"/><br>
<input type="submit" value="제출" /> <br>
<input type="reset" value="clear" /> <br>
</form>
</body>
</html>
코드 설명
- thymeleaf를 사용할 것이기 때문에, template 디렉토리에 "signup.html"을 생성해주었다.
- PostMapping을 해주기 위해서, form태그를 사용했다.
- id, password를 입력받는다.
- 버튼은 총 2가지로 submit, clear 버튼이 있다.
- submit은 post로 http요청을 하는 것이다.
- clear은 해당 form의 모든 영역에 입력된 값들을 지워주는 버튼이다.
- submit을 하면, "/signup"으로 post 요청을 한다.
※ 개발을 진행하면서 필요한 내용을 추가할 예정이다.
Sign up 컨트롤러 구현
코드를 살펴보자!
@Controller
@Slf4j
@RequiredArgsConstructor
public class SignUpContoller {
@Autowired
private final SignUpService signUpService;
@GetMapping("/signup")
public String signup(){
return "/signup";
}
@PostMapping("/signup")
public String signupForm(@ModelAttribute User user){
signUpService.signup(user);
return "redirect:/";
}
};
코드 설명
- Get, Post 매핑 2가지가 있다.
- Get은 기본 회원가입 영역을 return 해주기위한 메소드이다.
- Post는 회원가입 시, Post 방식으로 오게 될 내용을 처리하는 메소드이다.
- Post 요청 시, User로 받고 "signUpService"의 "signUp"메소드를 통해 비즈니스 로직을 실행한다.
- 비즈니스 로직 실행 후, 홈으로 리다이렉트한다.
User Repository 구현
User Repository는 실제로 DB에 엑세스하여 데이터를 다루는 중요한 부분이다.
코드를 보자!
public interface UserRepository extends JpaRepository<User, Long> {
//내용없음
};
코드 설명
- 기본적인 CRUD를 구현해놓은 JpaRepository를 사용하자!
- 계속해서 기능을 확장할 예정이다.
※ 의문점 : 프로젝트가 엄청나게 커지면 User 기능을 확장하면서 코드량이 많아질텐데 그때는 User를 분해를 하는건가? 쓸때없는 걱정같기도 하다.. ㅋㅋ
Sign Up Service 구현
Service는 실제 비즈니스 로직들을 가지고 있는 부분이다.
Repository를 사용하며, DB-비즈니스 로직-컨트롤러 부분을 나누기 위함이다.
코드를 보자!
@Service
@RequiredArgsConstructor
public class SignUpService {
@Autowired
private final UserRepository userRepository;
public void signup(User user){
userRepository.save(user);
}
};
코드 설명
- UserRepository를 @Autowired를 통해서 DI 받는다.
- signup 메소드를 통해서 insert를 수행한다.
완료되었다.
다음으로는 로그인을 해보자!!
300x250
Comments