When deleting data, can I find it with the delete method (key value to match, class name)?

Asked 2 years ago, Updated 2 years ago, 99 views

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

        // This part---------------------------------------------------------------------------------------------------------------------------------------------------
        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();
    }
}

The syntax is to access Student.java class from Hibernate to the constructor and delete it with the key value of id.

ex) delete(2); // delete Student data matching id=2.

If I write it like this, I think I need to create a lot of Delete methods for each class

So,

public static void delete (intid, String class name ) {

Class name stu = manager.find(class name.class,id);
}

As above, we tried to implement a single delete method by adding a variable as String class name and delete(3, Course)//(delete the course data matching id=3), but when we write the constructor, we have to input the class name ourselves. 클래스 When we declare the class constructor, can we receive it as a different variable and declaring the class constructor? I'd appreciate it if you could give me.

hibernate database method java

2022-09-22 15:36

1 Answers

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{...}

... ...

}

I couldn't see anything too simple because I was trying to put it too directly. I'm sorry.


2022-09-22 15:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.