μ΄λ²ˆμ—λŠ” 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" 으둜 잘 λ³€κ²½λœ 것을 λ³Ό 수 μžˆλ‹€.