The following annotated entity classes cause a NullPointerException to be thrown when creating an EntityManagerFactory:
package com.example;
import javax.persistence.*;
import java.util.Set;
@Entity
@Table(name = "A")
public class A {
@Id
@GeneratedValue
@OneToMany
@JoinColumn(name = "aid")
private Set<B> bs;
}
package com.example;
import javax.persistence.*;
@Entity
@Table(name = "B")
public class B {
@Id
@GeneratedValue
@Column(name = "bid")
private int bid;
@ManyToOne
@JoinColumn(name = "aid")
private A a;
}
The JPA persistence unit is defined as follows:
<?xml version="1.0"?>
<persistence 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"
version="2.0">
<persistence-unit name="example">
<class>com.example.A</class>
<class>com.example.B</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
</properties>
</persistence-unit>
</persistence>
When I run the following class
package com.example;
public class Main {
public static void main(String[] args) {
javax.persistence.Persistence.createEntityManagerFactory("example");
}
}
I get the following stacktrace written to the output:
The persistence unit is intentionally missing most of the database configuration. The NPE is reproducible with only the dialect, so I left out the rest of it in order to make the test case minimal. It makes no difference if you do add back the missing configuration, you still get an NPE. So it seems that the NPE is being thrown before Hibernate talks to the database.
In this situation I would much rather there was an exception thrown with a message explaining to me that I'm not using the annotations correctly. The NPE is not remotely helpful and goes no way at all to help a Hibernate novice find and fix their problem. In the above case, the fix is to uncomment the commented-out lines in class A. Once you do that, and restore the missing properties to the persistence unit, the NPE goes away and Hibernate works as expected.
This issue arose from a Stack Overflow question.
|