我按照一个有效的 JPA 示例来检索类别对象,如下所示:

return (ArrayList<Category>) getEntityManager().createQuery("from Category").getResultList();

该查询非常简写 - 我找不到任何指南中可选内容和不包含内容的规则。这种简洁可以接受吗?

其次,我现在想在通用 DAO 中实现这一点,例如:

public interface DAO<E, K>
{
    List<E> getAll();
}

由于我无法对“来自类别”进行硬编码,如何重写第一个查询以适用于所有类型?

有帮助吗?

解决方案

  1. 是的,简洁是可以接受的。虽然我更喜欢完整的语法,因为它对于其他有更多 SQL 经验的人来说更“有吸引力”。

  2. 你必须添加一个 Class<E> DAO 的参数:

    public List<E> getAll(Class<E> entityClass) {
         Query query = enittyManager.createQuery("from " + entityClass.getName());
         query.getResultList();
    }
    

其他提示

您实际上不必使用方法参数,但可以使用反射。

使用反射的示例代码

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class<T> DAO {         
    protected Class<T> clazz;

    public DAO()
    {
      Type genericSuperclass = getClass().getGenericSuperclass();
      // Allow this class to be safely instantiated with or without a parameterized type
      if (genericSuperclass instanceof ParameterizedType)
        clazz = (Class<T>) ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top