E aí pessoal, gostaria de pedir encarecidamente a ajuda de vocês pois estou há vários dias com esse problema, já tentei de tudo e não consegui dar jeito.
Tenho uma classe ManagedBean e nela utilizo um itemService para buscar todos os itens e assim carregar uma model, porém quando vou abrir a tela que puxa esse método de carregar a model, gera um erro de nullpointer exception, ao debugar percebi que o que está null é o itemService, ou seja, ele não está sendo instanciado/construído… Peço que considerem nas respostas que eu não sou muito experiente em java, portanto se puderem explicar o que estou errando e porquê seria ótimo! Vou colar aqui o erro e as classes relacionadas e desde já agradeço a atenção de todos. A organização do projeto é a seguinte:
MB > Service > ServiceImp > DAO > DAOImp (as DAOS extendem uma GenericDAO).
(este é meu primeiro post aqui, acabei de fazer o cadastro, caso eu tenha feito alguma besteira na formatação, desculpem!! )
MB:
[code]package controller;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.inject.Inject;
import dao.daoImp.ItemDAOImp;
import entity.ItemEntity;
import service.ItemService;
@SuppressWarnings(“serial”)
@ManagedBean(name = “itemMB”)
@ViewScoped
public class ItemMB implements Serializable {
@Inject
private ItemService itemService;
private DataModel<ItemEntity> modelItens;
private ItemEntity item;
private List<SelectItem> comboItens;
@PostConstruct
public void init() {
item = new ItemEntity();
}
/* AÇÕES */
public String salvar() {
try {
if (item.getIdItem() == 0) {
itemService.salvar(item);
} else {
itemService.salvar(item);
}
System.out.println("Salvo com sucesso!");
item = new ItemEntity();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Ocorreu um erro ao salvar.");
return null;
}
return null;
}
/* NAVEGAÇÃO */
public String cadastrar() {
item = new ItemEntity();
return null;
}
public String editar() {
this.item = modelItens.getRowData();
return null;
}
/* CARREGAR MODEL TIPO DOC */
@SuppressWarnings({ "unchecked", "rawtypes" })
public void carregarModelItens() {
this.modelItens = new ListDataModel(itemService.getAllItens());
}
@SuppressWarnings("unchecked")
public void carregarComboItens() {
comboItens = new ArrayList<SelectItem>();
try {
List<ItemEntity> result = itemService.getAllItens();
for (ItemEntity i : result) {
comboItens.add(new SelectItem(i, i.getNome()));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public ItemService getItemService() {
return itemService;
}
public void setItemService(ItemService itemService) {
this.itemService = itemService;
}
public DataModel<ItemEntity> getModelItens() {
return modelItens;
}
public void setModelItens(DataModel<ItemEntity> modelItens) {
this.modelItens = modelItens;
}
public ItemEntity getItem() {
return item;
}
public void setItem(ItemEntity item) {
this.item = item;
}
public List<SelectItem> getComboItens() {
return comboItens;
}
public void setComboItens(List<SelectItem> comboItens) {
this.comboItens = comboItens;
}
}
[/code]
Service e ServiceImp
package service;
import java.util.List;
import entity.ItemEntity;
public interface ItemService{
public void salvar(ItemEntity item);
public void excluir(int id);
@SuppressWarnings("rawtypes")
public List getAllItens();
public ItemEntity getItensById(int id);
}
package service.imp;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;
import dao.ItemDAO;
import entity.ItemEntity;
import service.ItemService;
@Stateless
public class ItemServiceImp implements ItemService{
@Inject
private ItemDAO itemDAO;
@Override
public void salvar(ItemEntity item) {
itemDAO.salvar(item);
}
@Override
public void excluir(int id) {
itemDAO.excluir(id);
}
@SuppressWarnings("rawtypes")
@Override
public List getAllItens() {
return itemDAO.getAllItens();
}
@Override
public ItemEntity getItensById(int id) {
return itemDAO.getItensById(id);
}
}
Classes DAO e DAO IMP
package dao;
import java.util.List;
import entity.ItemEntity;
public interface ItemDAO{
public abstract void salvar(ItemEntity item);
public abstract void excluir(int id);
public abstract List getAllItens();
public abstract ItemEntity getItensById(int id);
}
package dao.daoImp;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import dao.GenericDAO;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import org.hibernate.exception.GenericJDBCException;
import util.ConnectionManager;
import dao.ItemDAO;
import entity.ItemEntity;
@Stateless
public class ItemDAOImp extends GenericDAOImp<ItemEntity, Serializable> implements ItemDAO {
/**
*
*/
private static final long serialVersionUID = 1L;
private final static String SALVAR_ITEM = "INSERT INTO en_item (id, nome, descricao, valor) VALUES (?,?,?,?)";
private final static String DELETE_ITEM = "DELETE FROM en_item WHERE id = ?";
private final static String GET_ALL_ITENS = "SELECT * FROM en_item";
private final static String GET_ITEM_BY_ID = "SELECT * FROM en_item WHERE id = ?";
public ItemDAOImp() {
}
public void salvar(ItemEntity item) {
Connection conn = ConnectionManager.getConnection();
String sql = null;
if (item.getIdItem() == 0) {
sql = "INSERT INTO en_item (nome, descricao, valor) VALUES (?,?,?)";
} else {
sql = "UPDATE en_item SET nome = ?, descricao = ?, valor = ? WHERE id = ?";
}
try {
PreparedStatement pstmt;
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, item.getNome());
pstmt.setString(2, item.getDescricao());
pstmt.setInt(3, item.getValor());
// if (item.getIdItem() == 0)
// pstmt.setInt(4, item.getIdItem());
int resultado = pstmt.executeUpdate();
ConnectionManager.closeAll(conn, pstmt);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void excluir(int id) {
Connection conn = ConnectionManager.getConnection();
String sql = null;
sql = "DELETE FROM en_item WHERE idItem = ?";
try {
PreparedStatement pstmt;
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
int resultado = pstmt.executeUpdate();
ConnectionManager.closeAll(conn, pstmt);
} catch (SQLException e) {
e.printStackTrace();
}
}
@SuppressWarnings("rawtypes")
public List getAllItens() {
String sql = "SELECT * FROM en_item";
Connection conn = null;
ResultSet rs = null;
Statement stmt = null;
List<ItemEntity> itens = new ArrayList<ItemEntity>();
try {
conn = ConnectionManager.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
ItemEntity item = new ItemEntity();
item.setIdItem(rs.getInt("idItem"));
item.setNome(rs.getString("nome"));
item.setDescricao(rs.getString("descricao"));
item.setValor(rs.getInt("valor"));
itens.add(item);
}
}
catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeAll(conn, stmt, rs);
}
return itens;
}
public ItemEntity getItensById(int id) {
// TODO Auto-generated method stub
return null;
}
}
e por ultimo a genericDAO e genericDAOImp
package dao;
import java.io.Serializable;
import java.util.List;
public interface GenericDAO<T, I extends Serializable> {
public T save(T entity);
public void remove(T entity);
public void executeQuery(String query);
public T getById(Class<T> classe, I pk);
public List<T> getAll(Class<T> classe);
public List<T> getAllActive(Class<T> classe);
public List<T> getListOnQuery(String query);
public T getOnQuery(String query);
}
package dao.daoImp;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
public class GenericDAOImp<T, I extends Serializable> implements dao.GenericDAO<T, I>, Serializable {
private static final long serialVersionUID = 1L;
@PersistenceContext
protected EntityManager em;
public T save(T entity) {
T saved = null;
saved = em.merge(entity);
return saved;
}
public void remove(T entity) {
em.remove(entity);
}
public void executeQuery(String query) {
em.createQuery(query).executeUpdate();
}
public T getById(Class<T> classe, I pk) {
return em.find(classe, pk);
}
@SuppressWarnings("unchecked")
public List<T> getAll(Class<T> classe) {
try {
return em.createQuery("SELECT o FROM " + classe.getSimpleName() + " o").getResultList();
} catch (NoResultException ex) {
return null;
}
}
@SuppressWarnings("unchecked")
public List<T> getAllActive(Class<T> classe) {
try { //Busca todos desde que estejam ativos
return em.createQuery("SELECT o FROM " + classe.getSimpleName() + " o WHERE ativo = 1").getResultList();
} catch (NoResultException ex) {
return null;
}
}
@SuppressWarnings("unchecked")
public List<T> getListOnQuery(String query) {
try {
return em.createQuery(query).getResultList();
} catch (NoResultException ex) {
return null;
}
}
@SuppressWarnings("unchecked")
public T getOnQuery(String query) {
try {
return (T) em.createQuery(query).getSingleResult();
} catch (NoResultException ex) {
return null;
}
}
}
EDIT: Faltou postar o erro hehe
Segue:
javax.servlet.ServletException
javax.faces.webapp.FacesServlet.service(FacesServlet.java:606)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
controller.ItemMB.carregarModelItens(ItemMB.java:70)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:497)
javax.el.BeanELResolver.invoke(BeanELResolver.java:183)
javax.el.CompositeELResolver.invoke(CompositeELResolver.java:161)
org.apache.el.parser.AstValue.getValue(AstValue.java:174)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
com.sun.faces.facelets.el.ELText$ELTextVariable.toString(ELText.java:217)
com.sun.faces.facelets.compiler.AttributeInstruction.write(AttributeInstruction.java:89)
com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:82)
com.sun.faces.facelets.compiler.UILeaf.encodeAll(UILeaf.java:183)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:424)
com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:124)
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)