AbstractMethodError when creating typed query with

2019-05-11 23:27发布

问题:

I'm using Hibernate and JPA for a small project.

Somehow when trying to obtain an typed Query, the

java.lang.AbstractMethodError: org.hibernate.ejb.EntityManagerImpl.createQuery(Ljava/lang/String;Ljava/lang/Class;)Ljavax/persistence/TypedQuery

is thrown; org.hibernate.ejb.EntityManagerImpl is from hibernate-entitymanager-3.3.2.GA.jar .

This is not okay throwing the above exception:

  public Account read(Account entity) {
        EntityManager em = ManagedEntityManagerFactory.getEntityManager();

        String jpql = JPQLGenerator.readAccount();
        TypedQuery<Account> typedQuery =
                em.createQuery(jpql, Account.class);
        typedQuery.setParameter("accountId", entity.getAccountId());
        return typedQuery.getSingleResult();
    }

This is okay, however:

public Account read(Account entity) {
    EntityManager em = ManagedEntityManagerFactory.getEntityManager();

    String jpql = JPQLGenerator.readAccount();

    Query query =
            em.createQuery(jpql);
    query.setParameter("accountId", entity.getAccountId());
    Account account = null;
    Object obj = query.getSingleResult();
    if(obj instanceof Account) {
        account = (Account)obj;
    }
    return account;
}

回答1:

You have quite a mix of Hibernate and JPA versions. In subject line you mention Hibernate version 3.6.3 and JPA version 2.0. According body text EntityManagerImpl is version 3.3.2.GA. This mesh up with versions causes your problem.

TypedQuery was introduced in JPA 2.0 and Hibernate implements this specification since 3.5.X. Now you have EntityManager interface with

<T> TypedQuery<T> createQuery(CriteriaQuery<T> criteriaQuery)

but actual implementation does not implements such a method. That's why you get AbstractMethodError. Your second query works fine, because it uses JPA 1.0 constructs with one of the it's implementations (3.3.2.GA.) Just use implementation from Hibernate version 3.6.3 (or better even never).