CRUD 의 Create λ‹¨κ³„μ—μ„œ λ³΄μ•˜λ“―μ΄, 이번 Read μ—­μ‹œ λΉ„μŠ·ν•œ process 둜 development ν•˜λ©΄ λœλ‹€. 과정은 λ‹€μŒκ³Ό κ°™λ‹€.

  1. DAO Interface 에 μƒˆλ‘œμš΄ method μΆ”κ°€
  2. DAO Implementation 에 ν•΄λ‹Ή method implement
  3. main app 을 update
Step 1: Add new method to DAO Interface
import com.lucvs.cruddemo.entity.Student;
 
public interface StudentDAO {
	...
	Student findById(Integer id);
}

id λ₯Ό argument 둜 μ‚¬μš©ν•˜λŠ” findById λ₯Ό declare ν•œλ‹€.

Step 2: Define DAO Implementation
public class StudentDAOImpl implements StudentDAO {
	private EntityManager entityManager;
	...
 
	@Override
	public Student findById(Integer id) {
		return entityManager.find(Student.class, id);
	}
}

entityManager.find λ₯Ό μ‚¬μš©ν•˜μ—¬ parameter 둜 받은 id 값을 κΈ°μ€€μœΌλ‘œ, Student entity class 에 λŒ€ν•œ table μ—μ„œ ν•΄λ‹Ήν•˜λŠ” row λ₯Ό μ°ΎλŠ”λ‹€. λ§Œμ•½ id 에 ν•΄λ‹Ήν•˜λŠ” row κ°€ μ—†λ‹€λ©΄, null 을 return ν•œλ‹€.

μœ„ μ½”λ“œμ—μ„œ λ³Ό 수 μžˆλ“―μ΄ Create λ‹¨κ³„μ˜ Implementation μ—μ„œλŠ” @Transactional annotation 을 ν†΅ν•˜μ—¬ Create κ΄€λ ¨ method 에 λŒ€ν•œ μž‘μ—…μ΄ atomic ν•˜κ²Œ μˆ˜ν–‰λ˜λ„λ‘ ν•˜μ˜€λ‹€.

κ·ΈλŸ¬λ‚˜, Read λ‹¨κ³„μ—μ„œλŠ” Database 의 data μžμ²΄λ‚˜ structure λ₯Ό λ³€κ²½ν•˜μ§€ μ•Šκ³  λ‹¨μˆœνžˆ reading 만 ν•˜κΈ° λ•Œλ¬Έμ— ꡳ이 @Transactional 을 μ‚¬μš©ν•˜μ—¬ Read 에 λŒ€ν•œ overhead λ₯Ό ν‚€μšΈ μ΄μœ κ°€ μ—†λ‹€. 즉, performance μ—μ„œμ˜ 이점을 μœ„ν•œ 것이닀.

Step 3: Update Main Application
@SpringBootApplication 
public class CruddemoApplication {
	public static void main(String[] args) {
		SpringApplication.run(CruddemoApplication.class, args);	
	}
 
	@Bean
	public CommandLineRunner commandLineRunner(StudentDAO studentDAO) {
		return runner -> {
			readStudent(studentDAO);
		}
	}
 
	private void readStudent(StudentDAO studentDAO) {
		...
		// retrieve student based on the id: primary key
		Student myStudent = studentDAO.findById(tempStudent.getId());
		System.out.println("Found the student: " + myStudent);
	}
}
Read - Test

Database λ₯Ό TRUNCATE λ₯Ό ν†΅ν•˜μ—¬ μ΄ˆκΈ°ν™”ν•˜κ³  ν•˜λ‚˜μ˜ object λ₯Ό μƒμ„±ν•˜μ—¬ μ €μž₯ν•œ λ’€, ν•΄λ‹Ή object λ₯Ό retrieve ν•˜λŠ” μ‹μœΌλ‘œ test λ₯Ό μ§„ν–‰ν•΄λ³΄μž.

μœ„μ™€ 같이 μ„±κ³΅μ μœΌλ‘œ μ €μž₯된 object 의 data λ₯Ό retrieve ν•œ 것을 λ³Ό 수 μžˆλ‹€.