데이터 삭제할 때, delete메소드(매칭시킬키값,클래스명) 으로 찾을수 있나요?
조회수 1246회
public static void delete (int id) {
// Create an EntityManager
EntityManager manager = ENTITY_MANAGER_FACTORY.createEntityManager();
EntityTransaction transaction = null;
try {
// Get a transaction
transaction = manager.getTransaction();
// Begin the transaction
transaction.begin();
// 이 부분------------------------------------------------------------------------------
Student stu = manager.find(Student.class, id);
// Delete the student
manager.remove(stu);
// Commit the transaction
transaction.commit();
} catch (Exception ex) {
// If there are any exceptions, roll back the changes
if (transaction != null) {
transaction.rollback();
}
// Print the Exception
ex.printStackTrace();
} finally {
// Close the EntityManager
manager.close();
}
}
하이버네이트에서 생성자로 Student.java클레스로 접근해 id라는 키 값으로 delete 하는 구문인데요..
ex) delete(2); // id=2와 매칭되는 Student 데이터 삭제.
이렇게 쓰면 각 클래스별로 Delete 메소드를 많이 만들어야 할거 같은데요?
그래서
public static void delete (int id, String 클래스명) {
클래스명 stu = manager.find(클래스명.class, id);
}
위와같이 String 클래스명 으로 변수 추가해서 delete(2,Student), delete(3,Course)//(id=3과 매칭되는 Course데이터 삭제) 해서 delete 메소드 한개로 구현 하려했지만, 생성자쓸 때 클래스명을 직접 넣어야해서 에러가 납니다ㅠ 클래스 생성자 선언할때 위와 같이 다른 변수로 받아와서 클래스명을 구현할 수있을까요?? 조언좀 해주시면, 감사하겠습니다.
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
public static void delete (int id, String k) {
.... ...
if(k=="Student"){
Student stu = manager.find(Student.class, id);
...
}else if(k=="Course"){
Course cou = manager.find(Course.class, id);
...
}else if(k=="Score"){
Score sco = manager.find(Score.class, id);
... }else{...}
... ...
}
너무 직접적으로 대입하려다 보니 너무 간단한것도 잘 안보였네요.. 죄송합니다..
-
(•́ ✖ •̀)
알 수 없는 사용자
-
댓글 입력