I’m encountering an issue while trying to persist entities using Hibernate in my Java application. I have a straightforward setup with entity classes annotated with JPA annotations and a Hibernate session factory configured. However, when I attempt to save an entity using the session’s save()
method, I consistently encounter a NullPointerException
. Here’s a simplified version of my code
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Main {
private static SessionFactory factory;
public static void main(String[] args) {
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create session factory: " + ex);
throw new ExceptionInInitializerError(ex);
}
Session session = factory.openSession();
session.beginTransaction();
// Create and persist a new entity
MyEntity entity = new MyEntity();
entity.setName("Test Entity");
session.save(entity); // NullPointerException occurs here
session.getTransaction().commit();
session.close();
}
}
And here’s the entity class MyEntity
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
I’ve double-checked my Hibernate configuration and entity mappings, but I can’t seem to figure out why this NullPointerException
is happening. Any insights or suggestions would be greatly appreciated.