- Update a object
Student theStudent = entityManager.find(Student.class, 1);
// chage first name to 'PingPong'(setter를 이용)
theStudent.setFirstName("PingPong");
// Update the entity
entityManager.merge(theStudent);
entityManger.merge();
int numRowsUpdated = entityManager.createQuery("UPDATE Student SET lastName='Test'")
.executeUpdate();
Step1: Add new method to DAO interface
public interface StudentDAO {
// create
void save(Student theStudent);
//retrieve
Student findById(Integer id);
// query
List<Student> findAll();
// query LastName
List<Student> findByLastName(String theLastName);
//Update
void update(Student theStudent);
}
Step2: Add new method to DAO implementation
@Override
@Transactional // Since performing an update
public void update(Student theStudent) {
entityManager.merge(theStudent); //update the student
}
}
Step3: Update main app
@SpringBootApplication
public class HongdemoApplication {
public static void main(String[] args) {
SpringApplication.run(HongdemoApplication.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(StudentDAO studentDAO) {
return runner -> {
// createStudent(studentDAO);
// createMultipleStudent(studentDAO);
// readStudent(studentDAO);
// queryForStudents(studentDAO);
// queryForStudentsByLastName(studentDAO);
updateStudent(studentDAO);
};
}
private void updateStudent(StudentDAO studentDAO) {
// retrieve student based on the id; primary key
int studentId = 1;
System.out.println("Getting Student with id: " + studentId);
Student myStudent = studentDAO.findById(studentId);
// change first name to "DOG"
System.out.println("Updating students ...");
myStudent.setFirstName("Dog");
// update the students
studentDAO.update(myStudent);
// display the updated student
System.out.println("Updated students " + myStudent);
}