1
I have a problem, I am studying spring mvc with Hibernate and I ended up entering a bug where it returns the following exception "java.lang.Nullpointerexception", follows the codes:
Contactcontroller
package br.com.agenda.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import br.com.agenda.services.ContactService;
@Controller
@RequestMapping("/contact")
public class ContactController {
@RequestMapping(method=RequestMethod.GET)
public ModelAndView listContact() {
ContactService contactService = new ContactService();
ModelAndView modelAndView = new ModelAndView("contacts");
modelAndView.addObject("contacts", contactService.listAll());
return modelAndView;
}
}
Icontactservice
package br.com.agenda.interfaces;
import java.util.List;
import br.com.agenda.models.Contact;
public interface IContactService {
public void save(Contact contact);
public Contact searchId(Integer id);
public List<Contact> listAll();
public List<Contact> listSpecific(String field, String value);
}
Contactservice
package br.com.agenda.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import br.com.agenda.daos.ContactDAO;
import br.com.agenda.interfaces.IContactService;
import br.com.agenda.models.Contact;
public class ContactService implements IContactService {
@Autowired
private ContactDAO contactDAO = new ContactDAO();
public void save(Contact contact) {
contactDAO.save(contact);
}
public Contact searchId(Integer id) {
return contactDAO.search(id);
}
public List<Contact> listAll() {
return contactDAO.listAll();
}
public List<Contact> listSpecific(String field, String value) {
return null;
}
}
Contactdao
package br.com.agenda.daos;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import org.springframework.stereotype.Repository;
import br.com.agenda.models.Contact;
@Repository
public class ContactDAO {
@PersistenceContext
private EntityManager manager;
public void save(Contact contact) {
try {
if (contact.getId() != null) {
manager.persist(contact);
} else {
manager.merge(contact);
}
} catch(RuntimeException e) {
System.out.println(e.getMessage());
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
public Contact search(Integer id) {
try {
return manager.find(Contact.class, id);
} catch(RuntimeException e) {
System.out.print(e.getMessage());
return null;
} catch(Exception e) {
System.out.println(e.getMessage());
return null;
}
}
public List<Contact> listAll() {
try {
return manager
.createQuery("select distinct(c) from tblContacts c join fetch c.phones", Contact.class)
.getResultList();
} catch(PersistenceException e) {
System.out.println(e.getMessage());
return null;
}
}
}
Contact
package br.com.agenda.models;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.validator.constraints.NotBlank;
import br.com.agenda.models.Phone;
@Entity
@Table(name="tblContacts")
public class Contact {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="idContacts")
private Integer id;
@NotBlank
@Column(name="nameContacts")
private String name;
@NotBlank
@Column(name="emailContacts")
private String email;
@ElementCollection
private List<Phone> phones;
public void addPhone(Phone phone) {
phones.add(phone);
}
public List<Phone> getPhones() {
return phones;
}
public void setPhones(List<Phone> phones) {
this.phones = phones;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Phone
package br.com.agenda.models;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.validator.constraints.NotBlank;
@Entity
@Table(name = "tblPhones")
@Embeddable
public class Phone {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="idPhones")
private Integer id;
@NotBlank
@Column(name="dddPhones")
private Integer ddd;
@NotBlank
@Column(name="numberPhones")
private Integer number;
public Integer getDdd() {
return ddd;
}
public void setDdd(Integer ddd) {
this.ddd = ddd;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
}
Stack of Errors
type Exception report
message Request processing failed; nested exception is java.lang.NullPointerException
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
br.com.agenda.daos.ContactDAO.listAll(ContactDAO.java:52)
br.com.agenda.services.ContactService.listAll(ContactService.java:23)
br.com.agenda.controllers.ContactController.listContact(ContactController.java:19)
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:498)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:220)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/8.5.11 logs.
-- Configuration Files --
Appwebconfiguration
package br.com.agenda.conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import br.com.agenda.controllers.IndexController;
import br.com.agenda.daos.ContactDAO;
@EnableWebMvc
@Configuration
@ComponentScan(basePackageClasses={IndexController.class, ContactDAO.class})
public class AppWebConfiguration extends WebMvcConfigurerAdapter {
//Configurado pasta raiz das viewers e o suffix .jsp para as mesmas que serão carregadas
@Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Jpaconfiguration
package br.com.agenda.conf;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
public class JPAConfiguration {
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
{
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] {"br.com.agenda.models"});
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource()
{
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/agenda");
dataSource.setUsername("root");
dataSource.setPassword("");
return dataSource;
}
private Properties additionalProperties()
{
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "update");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
properties.setProperty("hibernate.show_sql", "true");
return properties;
}
@Bean
public PlatformTransactionManager transactionManager (EntityManagerFactory emf)
{
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
}
Servletspringmvc
package br.com.agenda.conf;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class ServletSpringMVC extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses()
{
return null;
}
//definido de onde vira as cofiguracoes para rodar as classes
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{AppWebConfiguration.class, JPAConfiguration.class};
}
//indica a pasta raiz mappeando o servlet
@Override
protected String[] getServletMappings()
{
return new String[] {"/"};
}
}
Help me and/or make the corrections please, since thank you.
Edit the question and add the stack of errors too.
– user28595
Was edited @diegofm.
– Marcos Paulo