Nullpointer Exception при попытке создать регистр в базе данныхJAVA

Программисты JAVA общаются здесь
Anonymous
Nullpointer Exception при попытке создать регистр в базе данных

Сообщение Anonymous »

Я новичок, используя JPA, я наметил свои занятия с ним, и теперь я пытаюсь создать регистр из одного класса, но у меня есть эта ошибка. Как я должен инициализировать ЭДФ? Я попытался инициализировать EMF, например EMF = Persistence.CreateEntityManagerFactory ("persistence_Unit"); , но не работает, удаляя частную EntityManagerFactory emf = null ни тоже.
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)
< /code>
roljpacontroller < /p>

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 findRolEntities() {
return findRolEntities(true, -1, -1);
}

public List findRolEntities(int maxResults, int firstResult) {
return findRolEntities(false, maxResults, firstResult);
}

private List 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 rt = cq.from(Rol.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}

}

< /code>
PersistenceController < /p>

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); }

}

< /code>
logiccontroller < /p>

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); }

}

< /code>
main < /p>
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);

}

}

< /code>
rol class < /p>

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 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 getActions() { return actions; }

public void setActions(Set actions) { this.actions = actions; }

}



Подробнее здесь: https://stackoverflow.com/questions/794 ... a-database

Вернуться в «JAVA»