[Spring Boot] Spring Data JPA를 이용한 CRUD

hameee·2024년 1월 8일
0

Spring Boot

목록 보기
18/20

📍 Create

  • 공통
    • JPA는 insert 시, insert한 엔티티를 리턴한다.
  • Controller
  • Service(BO)
    • 엔티티 생성 시, 빌더 패턴을 이용한다.
  • Repository
    • JpaRepository에서 save 메서드를 지원한다.

1) Controller

@RequestMapping("/lesson07/ex01")
@RestController
public class Lesson07Ex01RestController {

	@Autowired
	private StudentBO studentBO;
	
	@GetMapping("/1")
	public StudentEntity create() {
		return studentBO.addStudent("김바다", "010-1111-2222", "sbr@kakao.com", "개발자");
	}
    
}

2) Service(BO)

@Service
public class StudentBO {

	@Autowired
	private StudentRepository studentRepository;
	
	public StudentEntity addStudent(
			String name,
			String phoneNumber,
			String email,
			String dreamJob) {
		
		StudentEntity student = StudentEntity.builder()
				.name(name)
				.phoneNumber(phoneNumber)
				.email(email)
				.dreamJob(dreamJob)
				.build();
		
		return studentRepository.save(student);
	}
}

3) Repository

public interface StudentRepository extends JpaRepository<StudentEntity, Integer> {
	
}

📍 Read

  • 공통
  • Controller
  • Service(BO)
  • Repository
    • 작성 방법
      • JPQL을 사용하는 방법
        • JpaRepository의 기본 제공 메서드를 사용하는 방법
        • Spring Data JPA에서 제공하는 메서드 명명 규칙을 사용하는 방법
        • @Query(value = "JPQL 작성", nativeQuery = false)
      • SQL을 사용하는 방법(Native Query)
        • @Query(value = "SQL 작성", nativeQuery = true)
    • @Query 사용 시, 메서드 파라미터에 작성하는 @Param은 org.springframework.data.repository.query.Param에서 import해야 한다.(MyBatis에서 제공하는 @Param과 다름)
    • @Query에서 JSQL 작성 시, 엔티티명 대신 엔티티의 어노테이션 중 @Entity(name = "별칭")로 지정된 별칭을 사용할 수 있다.

👉 JPQL

  • Java Persistence Query Language
  • JPA에서 제공하는 객체 지향 쿼리 언어이다.
  • SQL과 유사하지만, 테이블이 아닌 엔터티 객체에 대한 쿼리를 작성할 수 있다.

1) Controller

@RequestMapping("/lesson07/ex02")
@RestController
public class Lesson07Ex02RestController {

	@Autowired
	private StudentBO studentBO;

	@GetMapping("/1")
	public StudentEntity ex2_1() {
		return studentBO.ex2_1(5);
	}
	
	@GetMapping("/2")
	public List<StudentEntity> ex2_2() {
		return studentBO.ex2_2("개발자");
	}
	
	@GetMapping("/3")
	public List<StudentEntity> ex2_3() {
		return studentBO.ex2_3("개발자");
	}
	
	@GetMapping("/4")
	public List<StudentEntity> ex2_4() {
		return studentBO.ex2_4("개발자");
	}
	
}

2) Service(BO)

@Service
public class StudentBO {
	
	@Autowired
	private StudentRepository studentRepository;
	
	public StudentEntity ex2_1(int id) {
		return studentRepository.findById(id).orElse(null);
	}
	
	public List<StudentEntity> ex2_2(String dreamJob) {
		return studentRepository.findByDreamJob(dreamJob);
	}
	
	public List<StudentEntity> ex2_3(String dreamJob) {
		return studentRepository.aaaa(dreamJob);
	}
	
	public List<StudentEntity> ex2_4(String dreamJob) {
		return studentRepository.bbbb(dreamJob);
	}
	
}

3) Repository

public interface StudentRepository extends JpaRepository<StudentEntity, Integer> {

	// JpaRepository의 기본 제공 메서드를 사용하는 방법
	// 메서드 정의 X
	
	// Spring Data JPA에서 제공하는 메서드 명명 규칙을 사용하는 방법
	public List<StudentEntity> findByDreamJob(String dreamJob);
	
	// @Query(value = "JPQL 작성", nativeQuery = false)
    // nativeQuery = false가 기본값이므로 생략 가능
	@Query(value = "select st from StudentEntity st where st.dreamJob = :dreamJob")
	public List<StudentEntity> aaaa(@Param("dreamJob") String dreamJob);
	
	// @Query(value = "SQL 작성", nativeQuery = true)
	@Query(value = "select * from new_student where dreamJob = :dreamJob", nativeQuery = true)
	public List<StudentEntity> bbbb(@Param("dreamJob") String dreamJob);
}

📍 Update

  • 공통
    • JPA는 update 시, update한 엔티티를 리턴한다.
  • Controller
  • Service(BO)
    • select 후, 해당 엔티티가 존재한다면 update를 실행한다.
    • toBuilder 메서드로 특정 필드만 수정한다.(엔티티에 @Builder(toBuilder = true) 설정이 되어있어야 함)
  • Repository
    • JpaRepository에서 save 메서드를 지원한다.

1) Controller

@RequestMapping("/lesson07/ex01")
@RestController
public class Lesson07Ex01RestController {

	@Autowired
	private StudentBO studentBO;
	
	@GetMapping("/2")
	public StudentEntity update() {
		return studentBO.updateStudentDreamJobById(5, "디자이너");
	}
    
}

2) Service(BO)

@Service
public class StudentBO {

	@Autowired
	private StudentRepository studentRepository;

	public StudentEntity updateStudentDreamJobById(int id, String dreamJob) {
    
		StudentEntity student = studentRepository.findById(id).orElse(null);
        
		if(student != null) {
			student = student.toBuilder()
				.dreamJob(dreamJob)
				.build();
                
			student = studentRepository.save(student);
		}
        
		return student;
        
	}
}

3) Repository

public interface StudentRepository extends JpaRepository<StudentEntity, Integer> {
	
}

📍 Delete

  • 공통
    • JPA는 delete 시, 아무것도 리턴하지 않는다.
  • Controller
  • Service(BO)
    • 작성 방법
      • 엔티티로 받는 방법(if문 사용)
      • Optional로 받는 방법(ifPresent 메서드 사용)
    • select 후, 해당 엔티티가 존재한다면 delete를 실행한다.
  • Repository

1) Controller

@RequestMapping("/lesson07/ex01")
@RestController
public class Lesson07Ex01RestController {

	@Autowired
	private StudentBO studentBO;
	
	@GetMapping("/3")
	public String delete() {
		studentBO.deleteStudentById(6);
		return "삭제 완료";
	}
    
}

2) Service(BO)

  • 엔티티로 받는 방법(if문 사용)

    @Service
    public class StudentBO {
    
    	@Autowired
    	private StudentRepository studentRepository;
    	
    	public void deleteStudentById(int id) {
      
    		StudentEntity student = studentRepository.findById(id).orElse(null);
    		if(student != null) {
    			studentRepository.delete(student);
    		}
          
    	}
    }
  • Optional로 받는 방법(ifPresent 메서드 사용)

    @Service
    public class StudentBO {
    
    	@Autowired
    	private StudentRepository studentRepository;
    	
    	public void deleteStudentById(int id) {
    		
    		Optional<StudentEntity> studentOptional = studentRepository.findById(id);
    		studentOptional.ifPresent(s -> studentRepository.delete(s));
          
    	}
    }

3) Repository

public interface StudentRepository extends JpaRepository<StudentEntity, Integer> {
	
}

0개의 댓글