-2
I have a problem that I believe is simple, but I’m having a hard time.
To be more clear, I will summarize the idea of the project: I have a Client class and an Update class.
The update class has as attribute Client, where it is inserted in the database a new update and linked to the client, at first I made the mapping Manytoone and try to search the client according to the CNPJ that comes via JSON in the update class, however the code always return NULLPOINTEREXCEPTION.
I happen to have the method in the customer service class and I can fetch the customer via CNPJ, and if not, it returns NULL and I can compare, if it is NULL then REGISTER the customer... Only when I try to get it directly from the Update class return the NULLPOINTEREXCEPTION.
NOTE: The error occurs when trying to fetch the client by CNPJ in the service class UPDATE
Follow below the error:
java.lang.NullPointerException: null
at projeto.KGClientes.clientes.service.AtualizacaoService.salvar(AtualizacaoService.java:30) ~[classes/:na]
at projeto.KGClientes.clientes.service.AtualizacaoService$$FastClassBySpringCGLIB$$a8cdb507.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771) ~[spring-aop-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) ~[spring-aop-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367) ~[spring-tx-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118) ~[spring-tx-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) ~[spring-aop-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691) ~[spring-aop-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at projeto.KGClientes.clientes.service.AtualizacaoService$$EnhancerBySpringCGLIB$$de74feec.salvar(<generated>) ~[classes/:na]
at projeto.KGClientes.clientes.controller.AtualizacaoController.atualizacao(AtualizacaoController.java:26) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
Class UPGRADE
package projeto.KGClientes.clientes.entity;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "TB_Atualizacao")
public class Atualizacao{
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence_id_atualizacao")
@SequenceGenerator(name = "sequence_id_atualizacao", sequenceName = "sequence_id_atualizacao", allocationSize = 1)
@Column(name = "IdAtualizacao")
private Integer IdAtualizacao;
@JoinColumn(name = "FK_Cliente")
@ManyToOne
private Cliente Cliente;
@Column(name = "Revisao")
private String Revisao;
@Column(name = "UltimaAtualizacao")
private String Ultatuali;
@Column(name = "DataVersao")
private String Dataversao;
@Column(name = "NomeVersao")
private String Nomeversao;
@Column(name = "DataCompilacao")
private String Datacompilacao;
@Column(name = "HoraCompilacao")
private String Horacompilacao;
@Column(name = "RevisaoIndiceTabelas")
private String Revisaoindicestabelas;
@Column(name = "CriadoEm")
private String CriadoEm;
//Tabela responsavel por armazenar o horario do arquivo
//Parame.ini, comando linux (stat -c %Y), caso o horario
//gravado nesta variavel seja diferente do horario que o
//script enviar, grava uma nova atualizacao.
@Column(name = "Modificado")
private String Modificado;
public Atualizacao() {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); //Padrão da data
Date data = new Date();
CriadoEm = sdf.format(data); //Converte a data para String
}
//---------GETTERS AND SETTERS-------------//
public Integer getIdCliente() {
return IdAtualizacao;
}
public void setIdCliente(Integer idCliente) {
IdAtualizacao = idCliente;
}
public Cliente getCliente() {
return Cliente;
}
public void setCliente(Cliente cliente) {
Cliente = cliente;
}
public String getRevisao() {
return Revisao;
}
public void setRevisao(String revisao) {
Revisao = revisao;
}
public String getUltatuali() {
return Ultatuali;
}
public void setUltatuali(String ultatuali) {
Ultatuali = ultatuali;
}
public String getDataversao() {
return Dataversao;
}
public void setDataversao(String dataversao) {
Dataversao = dataversao;
}
public String getNomeversao() {
return Nomeversao;
}
public void setNomeversao(String nomeversao) {
Nomeversao = nomeversao;
}
public String getDatacompilacao() {
return Datacompilacao;
}
public void setDatacompilacao(String datacompilacao) {
Datacompilacao = datacompilacao;
}
public String getHoracompilacao() {
return Horacompilacao;
}
public void setHoracompilacao(String horacompilacao) {
Horacompilacao = horacompilacao;
}
public String getRevisaoindicestabelas() {
return Revisaoindicestabelas;
}
public void setRevisaoindicestabelas(String revisaoindicestabelas) {
Revisaoindicestabelas = revisaoindicestabelas;
}
public String getCriadoEm() {
return CriadoEm;
}
public void setCriadoEm(String criadoEm) {
CriadoEm = criadoEm;
}
public Integer getIdAtualizacao() {
return IdAtualizacao;
}
public void setIdAtualizacao(Integer idAtualizacao) {
IdAtualizacao = idAtualizacao;
}
public String getModificado() {
return Modificado;
}
public void setModificado(String modificado) {
Modificado = modificado;
}
}
Service class UPDATE
package projeto.KGClientes.clientes.service;
import java.util.List;
import javax.management.Query;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import projeto.KGClientes.clientes.entity.Atualizacao;
import projeto.KGClientes.clientes.entity.Cliente;
import projeto.KGClientes.clientes.repository.AtualizacaoRepository;
import projeto.KGClientes.clientes.repository.ClienteRepository;
@Service
public class AtualizacaoService {
@Autowired
private AtualizacaoRepository atualizacaoRep;
private ClienteService clienteServ;
@Transactional
public Atualizacao salvar(Atualizacao atualizacao) {
//Localiza o cliente
atualizacao.setCliente(clienteServ.buscarClienteCNPJ("77962827000100"));**
*//O ERRO DE NULLPOINTER OCORRE NESTA LINHA, AO TENTAR LOCALIZAR O CLIENTE PELO CNPJ
//Localiza se ja tem alguma atualizacao com o mesmo valor do campo "Modificado"
Atualizacao a = atualizacaoRep.findByModificado(atualizacao.getModificado());
//Grava o cliente encontrado com o CNPJ informado
//atualizacao.setCliente(c);
if(a.getModificado() == atualizacao.getModificado()) {
//Essa atualizacao ja foi adicionada, exception
}
return atualizacaoRep.save(atualizacao);
}
public List<Atualizacao> listar() {
return atualizacaoRep.findAll();
}
public void excluir(Atualizacao cliente) {
atualizacaoRep.delete(cliente);
}
public Atualizacao buscarPorId(Integer id) {
return atualizacaoRep.findById(id).get();
}
public void excluirPorId(Integer id) {
atualizacaoRep.deleteById(id);
}
}
CUSTOMER SERVICE CLASS
package projeto.KGClientes.clientes.service;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import projeto.KGClientes.clientes.entity.Atualizacao;
import projeto.KGClientes.clientes.entity.Cliente;
import projeto.KGClientes.clientes.repository.ClienteRepository;
@Service
public class ClienteService {
@Autowired
private ClienteRepository clienteRep;
@Transactional
public Cliente salvar(Cliente cliente) {
//if(cliente.getCpf() != null) {
// BusinessExceptionCode codigoErro = BusinessExceptionCode.ERR001;
// BusinessException b = new BusinessException(codigoErro);
// throw b;
//}
Cliente c = buscarClienteCNPJ(cliente.getCnpj());
if(!(c == null)){ //Ja cadastrado (nao nulo)
//CLIENTE JA CADASTRADO, EXCEPTION
return null;
}
return clienteRep.save(cliente);
}
public List<Cliente> listar() {
return clienteRep.findAll();
}
public void excluir(Cliente cliente) {
clienteRep.delete(cliente);
}
public Cliente buscarPorId(Integer id) {
return clienteRep.findById(id).get();
}
public Cliente buscarClienteCNPJ(String cnpj) { //Busca exata, deve ter o cnpj completo
return clienteRep.findByCnpj(cnpj);
}
}
And lastly, Client REPOSITORY class:
package projeto.KGClientes.clientes.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import projeto.KGClientes.clientes.entity.Cliente;
public interface ClienteRepository extends JpaRepository<Cliente, Integer> {
@Query(value = "SELECT * FROM tb_cliente c where c.cnpj = :cnpj", nativeQuery = true)
public Cliente findByCnpj(@Param("cnpj") String cnpj);
@Query(value = "SELECT * FROM tb_cliente c where c.idCliente = :id", nativeQuery = true)
public Cliente findByIdCliente(@Param("id") Integer id);
}
Hi Rafael, it wasn’t the same as the @Nullprt replied? What differs the two answers?
– Guilherme Nascimento
The difference is, I supplemented it with the missing note on Repository, I know his comment is right, but I also missed this note, and in order to avoid taking the risk of someone just seeing my comment and announcing only @Repository, I took his comment and supplemented it with what I saw was missing. I’m not looking to score by copying other people’s answers, I just thought there’s a chance they won’t see both comments. If you understand me, you say that my answer is useful.
– Rafael Silva
Okay, -1 removed. No one accused you of wanting to earn points, what was unclear was where it was different, but now it’s clear. Welcome.
– Guilherme Nascimento