来自主键的JPA查询类

时间:2015-12-04 10:54:40

标签: java jpa persistence

如果我拥有它的主键,我将如何查询实体的类?我不想检索整个对象,当我只对该对象的类感兴趣时,这似乎是不必要的。我试过了

SELECT o.dtype FROM MyEntity o WHERE id = ?1

但这不起作用。

3 个答案:

答案 0 :(得分:2)

这将为您提供实际的课程:

SELECT TYPE(e) FROM MyEntity e WHERE e.id = ?1
Class<?> clazz = entityManager.createQuery(query, Class.class)
    .setParameter(1, id)
    .getSingleResult();

以下为您提供鉴别值:

SELECT e.class FROM MyEntity e WHERE e.id = ?1
String discr = entityManager.createQuery(query, String.class)
    .setParameter(1, id)
    .getSingleResult();

答案 1 :(得分:0)

SELECT o.dtype FROM MyEntity o WHERE o.id = ?1

您使用MyEntity的别名为o使用o来定义列id

答案 2 :(得分:0)

实际上这个查询有效:

SELECT o.class FROM MyEntity o WHERE id = ?1

使用示例:

public static Class<? extends MyEntity> getClassOf(Long id) {
    TypedQuery<String> q = entityManager().createQuery(
            "SELECT o.class FROM MyEntity o WHERE id = ?1", 
            String.class);
    q.setParameter(1, id);
    q.setMaxResults(1);
    List<String> r = q.getResultList();
    if (r.size() == 0)
        return null;

    for (Package p : Package.getPackages()){
        if (p.getName().startsWith("mypackage.prefix")){
            try {
                return (Class<? extends MyEntity>) Class.forName(p.getName() + "." + r.get(0));
            } catch (ClassNotFoundException e) {
                continue;
            }
        }
    }
    return null;
}