이번에는 CRUD 중 Update 에 대한 내용이다.
Update a Student
하나의 Student object 에 대하여 JPA 를 사용해 FirstName 을 update 하는 방법은 다음과 같다.
Student theStudent = entityManager.find(Student.class, 1);
// change first name to "John"
theStudent.setFirstName("John");
entityManager.merge(theStudent);Update last name for all students
int numRowsUpdated = entityManager.createQuery(
"UPDATE Student SET lastName='Tester'")
.executeUpdate();Student table 에 대하여 모든 row 의 lastName column 값을 Tester 로 변경하는 코드이다. executeUpdate() 를 통하여 해당 SQL statement 를 실행하고, 총 몇 개의 row 를 update 했는지를 return 값으로 받아서 numRowsUpdated 에 저장한다.
이전과 마찬가지로 세 가지 단계로 나누어 코드를 작성해보자.
Step 1: Add new method to DAO Interface
public interface StudentDAO{
...
void update(Student theStudent);
}Step 2: Define DAO Implementation
public class StudentDAOImpl implements StudentDAO {
private EntityManager entityManager;
...
@Override
@Transactional
public void update(Student theStudent) {
entityManager.merge(theStudent);
}
}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 -> {
updateStudent(studentDAO);
}
}
private void updateStudent(StudentDAO studentDAO) {
...
// retrieve student based on the id: primary key
Student myStudent = studentDAO.findById(tempStudent.getId());
// change first name to "John"
myStudent.setFirstName("John");
studentDAO.update(myStudent);
}
}Update - Test

위와 같이, id 값이 1 인 object 에 대하여 firstName 을 "John" 으로 잘 변경된 것을 볼 수 있다.