0

I am using JPA Criteria API with JPA meta model.

final CriteriaBuilder cb = em.getCriteriaBuilder();
final CriteriaQuery<T> criteria = cb.createQuery(User.class);
final Root<T> root = criteria.from(User.class);
criteria.select(root).where(cb.equal(root.get(User_.username), value));
return em.createQuery(criteria).getResultList();

here the problem is root.get method throws NPE first time after the server starts (i.e first execution after server start), but the same code works fine from second execution onwards. It doesn't matter when the first execution executed after server started. It may be executed after few seconds or after few minutes.

Following is the exception thrown:

java.lang.NullPointerException: null
    at org.apache.openjpa.persistence.criteria.PathImpl.get(PathImpl.java:245) ~[openjpa-2.4.2.jar:2.4.2]

If you look at the source code of PathImpl.get

public <Y> Path<Y> get(SingularAttribute<? super X, Y> attr) {
    if (getType() != attr.getDeclaringType()) {
        attr = (SingularAttribute)((ManagedType)getType()).getAttribute(attr.getName());
    }
    return new PathImpl<X,Y>(this, (Members.SingularAttributeImpl<? super X, Y>)attr, attr.getJavaType());
}

it access attr.getDeclaringType()

If I look at the JPA meta model which is auto generated it looks as follows:

public class User_ {
    public static volatile SingularAttribute<User,String> username;
    ...
}

username is definitely null, however the code works well except first time.

It appears during runtime JPA set value to User_.username.

so question is how do prevent throwing NPE first time!

Using TomEE 7.0.4

yottabrain
  • 2,387
  • 5
  • 23
  • 37
  • Have you tried all of the suggestions from https://stackoverflow.com/questions/3854687/jpa-hibernate-static-metamodel-attributes-not-populated-nullpointerexception? – crizzis Dec 23 '17 at 12:29
  • Thanks you! That issue talks about getting NPE always, which is not the case for me. It throws NPE only first execution. Also I already have model and meta model in same package as described in the solution of that issue. I also read other answers. – yottabrain Dec 23 '17 at 12:39
  • In which context do you have this code that fails? Some bean or what? – pirho Dec 23 '17 at 12:53
  • @user1734143 If none of the solutions worked, then I'd venture to say this is a bug in the JPA provider. At risk of sounding biased against OpenJPA, I'd strongly suggest trying a different one. – crizzis Dec 23 '17 at 12:55
  • Alternatively, if this is really the case that only the first try fails, it would seem they're supposed to initialize upon first reference, in which case you could try explicitly referencing them before using them for the criteria query. – crizzis Dec 23 '17 at 12:56

0 Answers0