I'm new using JPA, I mapped my classes with it, and now I'm trying to create a register from one class but I have this error. How I should to initialize emf? I tried to initialize emf like emf = Persistence.createEntityManagerFactory("PERSISTENCE_UNIT");
but doesn't works, removing private EntityManagerFactory emf = null
neither.
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "jakarta.persistence.EntityManagerFactory.createEntityManager()" because "this.emf" is null
at org.persistence.RolJpaController.getEntityManager(RolJpaController.java:32)
at org.persistence.RolJpaController.create(RolJpaController.java:38)
at org.persistence.PersistenceController.createRol(PersistenceController.java:26)
at org.logic.LogicController.createRol(LogicController.java:11)
at org.logic.Main.main(Main.java:14)
RolJpaController
package org.persistence;
import jakarta.persistence.*;
import java.io.Serializable;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import java.util.List;
import org.logic.Rol;
import org.persistence.exceptions.NonexistentEntityException;
public class RolJpaController implements Serializable {
public RolJpaController(EntityManagerFactory emf) {
this.emf = emf;
}
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Rol rol) {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(rol);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Rol rol) throws NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
rol = em.merge(rol);
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Long id = rol.getId();
if (findRol(id) == null) {
throw new NonexistentEntityException("The rol with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Long id) throws NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Rol rol;
try {
rol = em.getReference(Rol.class, id);
rol.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The rol with id " + id + " no longer exists.", enfe);
}
em.remove(rol);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public List<Rol> findRolEntities() {
return findRolEntities(true, -1, -1);
}
public List<Rol> findRolEntities(int maxResults, int firstResult) {
return findRolEntities(false, maxResults, firstResult);
}
private List<Rol> findRolEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Rol.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Rol findRol(Long id) {
EntityManager em = getEntityManager();
try {
return em.find(Rol.class, id);
} finally {
em.close();
}
}
public int getRolCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Rol> rt = cq.from(Rol.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
PersistenceController
package org.persistence;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import org.logic.Action;
import org.logic.Rol;
public class PersistenceController {
private static final String PERSISTENCE_UNIT = "IceCreamShopPU";
private static EntityManagerFactory emf;
public PersistenceController(){ emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT); }
ActionJpaController ActionJpa = new ActionJpaController(emf);
FlavorJpaController FlavorJpa = new FlavorJpaController(emf);
IceCreamJpaController IceCreamJpa = new IceCreamJpaController(emf);
InvoiceJpaController InvoiceJpa = new InvoiceJpaController(emf);
OrdenJpaController OrdenJpa = new OrdenJpaController(emf);
RolJpaController RolJpa = new RolJpaController(emf);
SizeJpaController SizeJpa = new SizeJpaController(emf);
UserJpaController UserJpa = new UserJpaController(emf);
public void createAction(Action act) { ActionJpa.create(act); }
public void createRol(Rol rol) { RolJpa.create(rol); }
}
LogicController
package org.logic;
import org.persistence.PersistenceController;
public class LogicController {
PersistenceController PersistenceCtl = new PersistenceController();
public void createAction (Action act){ PersistenceCtl.createAction(act); }
public void createRol(Rol rol){ PersistenceCtl.createRol(rol); }
}
Main
package org.logic;
import java.util.Date;
public class Main {
public static void main (String[] args){
LogicController LogicCtl = new LogicController();
Rol role = new Rol("admin", new Date());
LogicCtl.createRol(role);
}
}
Rol class
package org.logic;
import jakarta.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
@Entity
@Table(name = "rol")
public class Rol implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(length = 30, unique = true, name = "rol")
private String rol;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_at")
private Date created_at;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated_at")
private Date updated_at;
@ManyToMany(mappedBy = "roles")
private Set<Action> actions;
public Rol() {}
public Rol(String rol, Date created_at) {
this.rol = rol;
this.created_at = created_at;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getRol() { return rol; }
public void setRole(String rol) { this.rol = rol; }
public Date getCreated_at() { return created_at; }
public void setCreated_at(Date created_at) { this.created_at = created_at; }
public Date getUpdated_at() { return updated_at; }
public void setUpdated_at(Date updated_at) { this.updated_at = updated_at; }
public Set<Action> getActions() { return actions; }
public void setActions(Set<Action> actions) { this.actions = actions; }
}
i think it's cause the EntityManagerFactory (emf) is not properly initialized when RolJpaController is instantiated.
change your initialization to private final EntityManagerFactory emf;
Since emf is already initialized at the constructor, there is no need to declare a separate initialization.
try
public class PersistenceController { private static final String PERSISTENCE_UNIT = "IceCreamShopPU";
private static final EntityManagerFactory emf;
static {
emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
if (emf == null) { //to Debug the initialization
throw new RuntimeException("EntityManagerFactory failed to initialize!");
}
}
RolJpaController RolJpa = new RolJpaController(emf);
public void createRol(Rol rol) {
RolJpa.create(rol);
}
}`
public class RolJpaController implements Serializable {
private final EntityManagerFactory emf;
public RolJpaController(EntityManagerFactory emf) {
this.emf = emf;
}
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
// put the rest of your code here
}