Deleting Objects with JPA Overview
Delete a Student
// retrieve the student
int id = 1;
Student theStudent = entityManager.find(Student.class, id);
// delete the student
entityManager.remove(theStudent);
Delete based on a condition
Delete All Students
int numRowsDeleted = entityManager.createQuery("DELETE FROM Student").excuteUpdate();
Development Process
- Add new method to DAO interface
- Add new method to DAO implemen
- Update main app
Step 1: Add new method to DAO interface
public interface StudentDAO {
void delete(Integer id);
}
Step 2: Define DAO implementation
@Repository
public class StudentDAOImpl implements StudentDAO{
private EntityManager entityManager;
...
@Override
@Transactional // <- Add @Transactional since we are performing a delete
public void delete(Integer id) {
// retrieve the student
Student theStudent = entityManager.find(Student.class, id);
// delete the student
entityManager.remove(theStudent);
}
Step 3: Update main app
@SpringBootApplication
public class CruddemoApplication {
...
public CommandLineRunner commandLineRunner(StudentDAO studentDAO){
return runner-> {
deleteAllStudents(studentDAO);
};
}
private void deleteStudent(StudentDAO studentDAO) {
int studentId = 2;
System.out.println("Deleting student id: " + studentId);
studentDAO.delete(studentId);
}
Delete all of the students
public interface StudentDAO {
int deleteAll();
}
private void deleteAllStudents(StudentDAO studentDAO) {
System.out.println("Deleting all students");
int numRowsDeleted = studentDAO.deleteAll();
System.out.println("Deleted row count: " + numRowsDeleted);
}
댓글남기기