λ§ˆμ§€λ§‰μœΌλ‘œ Delete 에 λŒ€ν•œ λ‚΄μš©μ΄λ‹€.

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
int numRowsDeleted = entityManager.createQuery(
	"DELETE FROM Student WHERE lastName='Smith'"
	.executeUpdate();
)

μ—¬κΈ°μ„œ executeUpdate() μ—μ„œμ˜ update 에 λŒ€ν•œ μ˜λ―ΈλŠ” Database 에 λŒ€ν•œ modify λ₯Ό μ˜λ―Έν•œλ‹€κ³  λ³΄λ©΄λœλ‹€. numRowsDeleted λŠ” μ‚­μ œλœ row 의 개수 값을 μ €μž₯ν•œλ‹€.

Delete All Students
int numRowsDelete = entityManager.createQuery(
	"DELETE FROM Student"
	.executeUpdate();
)

λ‹€μŒμ€ Development Process 이닀.

Step 1: Add new method to DAO Interface
import com.lucvs.cruddemo.entity.Student;
 
public interface StudentDAO {
	...
	Student delete(Integer id);
}
Step 2: Define DAO Implementation
public class StudentDAOImpl implements StudentDAO {
	private EntityManager entityManager;
	...
 
	@Override
	@Transactional
	public Student delete(Integer id) {
		Student theStudent = entityManager.find(Student.class, id);
		entityManager.remove(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 -> {
			deleteStudent(studentDAO);
		}
	}
 
	private void deleteStudent(StudentDAO studentDAO) {
		// delete the student
		int studentId = 5;
		System.out.println("Deleting student id: " + studentId);
		studentDAO.delete(studentId);
	}
}
Delete - Test (delete a student)

μš°μ„  test λ₯Ό μœ„ν•˜μ—¬ μ•„λž˜μ™€ 같이 λͺ‡ 개의 object λ₯Ό Student table 에 μΆ”κ°€ν•˜μ˜€λ‹€.

μœ„μ˜ μƒνƒœμ—μ„œ id κ°€ 5 인 object λ₯Ό delete ν•΄λ³΄μž.

μ„±κ³΅μ μœΌλ‘œ id κ°€ 5 인 object κ°€ delete 된 것을 확인할 수 μžˆλ‹€.

Delete - Test (delete all student)

μ΄λ²ˆμ—λŠ” λͺ¨λ“  object λ₯Ό delete ν•˜λŠ” κΈ°λŠ₯을 μƒμ„±ν•˜μž.

μš°μ„  StudentDAO Interface 에 deleteAll() 을 declare ν•˜κ³ , StudentDAOImpl class μ—μ„œ deleteAll() method λ₯Ό λ‹€μŒκ³Ό 같이 define ν•œλ‹€.

@Override  
@Transactional  
public int deleteAll() {  
    return entityManager.createQuery("DELETE FROM Student").executeUpdate();  
}

그리고 Main Application μ—μ„œ deleteAllStudents() method λ₯Ό λ‹€μŒκ³Ό 같이 define ν•œλ‹€.

private void deleteAllStudent(StudentDAO studentDAO) {  
    System.out.println("Deleting all students");  
    int numRowsDeleted = studentDAO.deleteAll();  
    System.out.println("Deleted row count: " + numRowsDeleted);  
}

이제 Application 을 μ‹€ν–‰ν•˜μ—¬ test ν•΄λ³΄μž.

결과적으둜 DB Table 이 μ•„μ£Ό κΉ”λ”ν•˜κ²Œ delete 된 것을 λ³Ό 수 μžˆλ‹€.