CRUD μ Create λ¨κ³μμ 보μλ―μ΄, μ΄λ² Read μμ λΉμ·ν process λ‘ development νλ©΄ λλ€. κ³Όμ μ λ€μκ³Ό κ°λ€.
- DAO Interface μ μλ‘μ΄ method μΆκ°
- DAO Implementation μ ν΄λΉ method implement
- 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 ν κ²μ λ³Ό μ μλ€.