Updating Objects with JPA

류홍규·2023년 7월 5일
0

JPA

목록 보기
6/8

- 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();


⚾ Update last name for all students

int numRowsUpdated = entityManager.createQuery("UPDATE Student SET lastName='Test'")
.executeUpdate();
  • UPDATE ... SET
  • executeUpdate: execute this statement

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);
	}


profile
공대생의 코딩 정복기

0개의 댓글

관련 채용 정보