java - 如何在 Hibernate 删除操作中获取对象的类

标签 java hibernate

我有一个功能如下:

public boolean delete(int id) {

    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    em.remove(em.find(Student.class, id));
    em.getTransaction().commit();

    return true;
}

现在我希望上述函数是一个通用函数。所以我通过以下方式实现了相同的:

 public boolean genericDelete(int id, Object ob) {

     EntityManager em = emf.createEntityManager();
     em.getTransaction().begin();
     em.remove(em.find((Class) ob, id));
     em.getTransaction().commit();

     return true;
 }

该函数工作正常,没有任何缺陷,但 IntellijIDEA 提示对象被转换为类。这可能是一种不好的做法,那么如何以正确的方式实现呢?请帮忙...

最佳答案

不需要在那里 Actor 。 Java为此提供了直接的方法。

Class c = ob.getClass();

Oracle 文档:Retrieving Class Objects

If an instance of an object is available, then the simplest way to get its Class is to invoke Object.getClass(). Of course, this only works for reference types which all inherit from Object. Some examples follow.

Class c = "foo".getClass();

关于java - 如何在 Hibernate 删除操作中获取对象的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48594444/

相关文章:

java - Spring MVC : Controller method is not invoked

java - JPA @Converter 可以在使用 @MapKey 的 map 映射中使用吗?

java - 如何使用 PreparedStatement 创建列表?

java - <bpmndi :BPMNShape> Is Missing for participant and lane element in xml when trying to create pool and lane from java source

java - 有没有办法暂停/恢复 SwingWorker

spring - 严重 : StandardWrapper. 可抛出

spring hibernate 和使用 ehcache 进行缓存

java - Hibernate - 持久化多态连接

java - 为什么 Spring 中的 RestTemplate 必须传递参数名称

java - 如何制作一个接受任意命令的守护进程