Home » Java » java – Persistence.createEntityManagerFactory("something") returns null-Exceptionshub

java – Persistence.createEntityManagerFactory("something") returns null-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am learning JPA with sample project. Whenever I execute the program, it returns null. I checked follow

JPA – createEntityManagerFactory returns Null ,But,this is not helping. please help me. i have been stuck two days. I dont know where i do mistakes .

Following Exception is always happening,

1605 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanEnvironment [[email protected]82e36] into BootstrapContext; was [null]
1606 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanOptions [[email protected]906] into BootstrapContext; was [[email protected]fcc1]
Exception in thread "main" java.lang.NullPointerException
        at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.toClassDescriptor(ClassFileArchiveEntryHandler.java:84)
        at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.toClassDescriptor(ClassFileArchiveEntryHandler.java:67)
        at org.hibernate.boot.archive.scan.spi.ClassFileArchiveEntryHandler.handleEntry(ClassFileArchiveEntryHandler.java:53)
        at org.hibernate.boot.archive.internal.JarFileBasedArchiveDescriptor.visitArchive(JarFileBasedArchiveDescriptor.java:147)
        at org.hibernate.boot.archive.scan.spi.AbstractScannerImpl.scan(AbstractScannerImpl.java:47)
        at org.hibernate.boot.model.process.internal.ScanningCoordinator.coordinateScan(ScanningCoordinator.java:76)
        at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.prepare(MetadataBuildingProcess.java:98)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:242)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:175)
        at org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder(Bootstrap.java:76)
        at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:171)
        at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:119)
        at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:61)
        at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:50)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
        at com.test.jpa.App.main(App.java:19)

Main class

public class App 
{

    public static void main( String[] args )
    {
        System.out.println( "I am going to connect" );
        BasicConfigurator.configure();
        Logger.getLogger("org").setLevel(Level.ALL);

            EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("boom");
            if(entityManagerFactory !=null ) {
                 System.out.println( "lalala" );
            }else {
                 System.out.println( "nullllllllllllll" );
            }

    }
}

This is Mapping class,

package com.test.jpa;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name = "client")
public class User {

    @Column(name = "name")
    private String name = null;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Column(name = "age")
    private int age = 0;

    @Id
    @Column(name = "No")
    private int No = 0;

    public int getNo() {
        return No;
    }

    public void setNo(int no) {
     No = no;
   }
}

pom file

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.test</groupId>
  <artifactId>jpa</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>jpa</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

    <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
        <dependency>
             <groupId>org.slf4j</groupId>
             <artifactId>slf4j-api</artifactId>
             <version>1.7.30</version>
        </dependency>
        <dependency>
               <groupId>org.hibernate</groupId>
               <artifactId>hibernate-core</artifactId>
               <version>5.4.11.Final</version>
        </dependency>   
         <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901-1.jdbc4</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>    
            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <optimize>true</optimize>
                <debug>true</debug>
                <encoding>${project.build.sourceEncoding}</encoding>
            </configuration>
            </plugin>      
            <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-assembly-plugin</artifactId>
              <configuration>
                  <descriptorRefs>
                      <descriptorRef>jar-with-dependencies</descriptorRef>
                  </descriptorRefs>
                  <dependencySets>
                      <dependencySet>
                          <includes>
                              <include>*:jar:*</include>
                          </includes>
                          <excludes>
                              <exclude>*:sources</exclude>
                              <exclude>*:javadoc</exclude>
                          </excludes>
                      </dependencySet>
                  </dependencySets>
                 <archive>
                   <manifest>
                     <addClasspath>true</addClasspath>
                     <mainClass>com.test.jpa.App</mainClass>
                   </manifest>
                 </archive>
               </configuration>
                 <executions>
                     <execution>
                         <id>make-assembly</id>
                         <phase>package</phase>
                         <goals>
                             <goal>single</goal>
                         </goals>
                     </execution>
                 </executions>
            </plugin>        
        </plugins>
   </build>
</project>

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence  http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="boom"  >
     <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>  
    <class>com.test.jpa.User</class>
    <properties>
      <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:6767/User"/>
      <property name="javax.persistence.jdbc.user" value="postgres"/>
      <property name="javax.persistence.jdbc.password" value="atis"/>
     <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
      <property name="hibernate.show_sql" value="false"/>
      <property name="hibernate.format_sql" value="true"/>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
      <property name="hibernate.connection.autocommit" value="false"/>
      <property name="hibernate.connection.provider_disables_autocommit" value="true"/>
    </properties>
  </persistence-unit>
</persistence>

I created database with name User, table is “client” , cloumn are “No”,”age”-integer datatype, “name”-string datatype

update:

I tested with junit tool with follow class.

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class PersonTest {
    private EntityManagerFactory emf;

    private EntityManager em;

    @Before
    public void initEmfAndEm() {
        BasicConfigurator.configure();
        Logger.getLogger("org").setLevel(Level.ALL);

        emf = Persistence.createEntityManagerFactory("boom");
        if(emf !=null)
        System.out.println("wooooooooooooooooooooo ");
        em = emf.createEntityManager();
    }

    @After
    public void cleanup() {
        em.close();
    }

    @Test
    public void emptyTest() {
    }
}

When it gets executed, it is not throws null pointer exception. it prints like follow, then it passes to sucessive execution.

844 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanEnvironment [[email protected]5312be2] into BootstrapContext; was [null]
844 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanOptions [[email protected]95505] into BootstrapContext; was [[email protected]e6e8]
903 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting JPA temp ClassLoader [null] into BootstrapContext; was [null]
903 [main] DEBUG org.hibernate.boot.internal.ClassLoaderAccessImpl  - ClassLoaderAccessImpl#injectTempClassLoader(null) [was null]

But when execute using well packaged jar in command line,exeception is thrown

1605 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanEnvironment [[email protected]82e36] into BootstrapContext; was [null]
1606 [main] DEBUG org.hibernate.boot.internal.BootstrapContextImpl  - Injecting ScanOptions [[email protected]906] into BootstrapContext; was [[email protected]fcc1]
Exception in thread "main" java.lang.NullPointerException

thanks

How to&Answers:

I fixed problem .It was dependency problem. In pom file, After i added following

   <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.4.12.Final</version>
        </dependency>

and removed following dependency

<dependency>
               <groupId>org.hibernate</groupId>
               <artifactId>hibernate-core</artifactId>
               <version>5.4.11.Final</version>
        </dependency>   

hibernate-entitymanager will add all necessary dependency.

Answer:

Packing problem during build time

You configuration looks right. Probably it’s a packing problem. Try build and run you project with the following commands and it will work:

mvn clean compile assembly:single
java -jar target/jpa-0.0.1-SNAPSHOT-jar-with-dependencies.jar

Take a look this answer to see more about how to create a jar with dependencies.
Maven – Build with Dependencies

More details for the sake of correctness:

org.hibernate:hibernate-core is the right dependecy to be used.
org.hibernate:hibernate-entitymanager is deprecated and actually only points to hibernate-core.

Reference inside jar:

Hibernate’s JPA support has been merged into the hibernate-core
module, making this hibernate-entitymanager module obsolete. This
module will be removed in Hibernate ORM 6.0. It is only kept here for
various consumers that expect a static set of artifact names across a
number of Hibernate releases. See
https://hibernate.atlassian.net/browse/HHH-10823