Search code examples
javajpaeclipselink

NullPointerException in EclipseLink initialization


I am using Eclipselink 2.6.0-RC2 from maven repository and trying on the inheritance.

I have the 3 classes below:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(discriminatorType = DiscriminatorType.STRING, name = "CLASSNAME")
public abstract class Project {
    @Id
    @Column(length = 50)
    private String id;
}

@Entity
@DiscriminatorValue(value = "Foo")
public class FooProject extends Project {
    private static EntityManagerFactory emf = Persistence
        .createEntityManagerFactory("vasp");
    private static EntityManager em = emf.createEntityManager();


    public static void main(String[] args) {
    }
}

@Entity
@DiscriminatorValue(value = "Bar")
public class BarProject extends Project {
    private static EntityManagerFactory emf = Persistence
        .createEntityManagerFactory("vasp");
    private static EntityManager em = emf.createEntityManager();

    public static void main(String[] args) {
    }
}

For the above configuration, both main in FooProject and BarProject failed with the following exception

Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: javax.persistence.PersistenceException: java.lang.NullPointerException
    at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:812)
    at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:205)
    at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.createEntityManagerImpl(EntityManagerFactoryDelegate.java:305)
    at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:337)
    at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:303)

If I removed @Entity description on BarProject then main on FooProject does not fail, and vise versa.

I have tried removing abstract in Project and assign it a @DiscriminatorValue, but it doesn't work.

If the main is placed in Project, it never worked too.

Is there any mistake in the annotation I am using that prevented it to work?


Solution

  • Remove references to EntityManagerFactory and EntityManager from entities, move it to some new class along with main() method and try again.

    In order for persistence unit to be initialized, all entities must be initialized and scanned. Your setup interferes with that, with PU initializing in static variables, I wouldn't go into analysis why it works in one case and not in another since it is just wrong. Using entity manager inside entities is considered an anti-pattern by many (me included), but you'll find open debates on it on the web.