java.lang.Classcastexception: class java.lang.Integer cannot be cast to class java.lang.Void

Asked

Viewed 206 times

-1

I am trying to perform an UPDATE in the User table, but when doing Ubmit error occurs. I’m having a hard time understanding what the mistake is about, could you help me? below is my code and the error that is occurring.

Page:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
        xmlns:th="http://www.thymeleaf.org"
        xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
        layout:decorate="~{LayoutPadrao}">
<head>
    <title>Cadastro Usuario</title>
</head>
<section layout:fragment="conteudo">
    <div th:class="${classe}" th:if="${!#strings.isEmpty(mensagem)}">
        <span th:text="${mensagem}">Mensagem vem do Controller</span>
    </div>
    <form class="card" th:method="${action} == editar ? 'PUT' : 'POST'" th:action="${action} == 'editar' ? @{/usuario/editar/{codigo}(codigo=${usuario.getId_Usuario()})} : @{/usuario/salvarUsuario}" th:object="${usuario}">
        <h5 class="card-header">Cadastro de Usuário</h5>
        <div class="card-body">
            <input type="hidden" name="id_usuario" th:value="${usuario.getId_Usuario()}"/>
            <div class="form-group">
                <label for="txtUsuario">Usuário</label>
                <input type="text" required class="form-control col-md-6" id="txtUsuario" name="usuario" th:field="*{usuario}" placeholder="Usuario"/>
            </div>
            <div class="form-group">
                <label for="txtSenha">Senha</label>
                <input type="password" required class="form-control col-md-6" id="txtSenha" name="senha" th:field="*{senha}" placeholder="Senha"/>
            </div>
            <div class="form-group">
                <label for="txtEmail">E-mail</label>
                <input type="email" required class="form-control col-md-6" id="txtEmail" name="email" th:field="*{email}" placeholder="[email protected]"/>
            </div>
            <div class="form-group">
                <label for="dataCadastro" class="">Data de Cadastro</label>
                <div>
                    <input type="text" required class="form-control col-sm-2"   id="dataCadastro" name="dataCadastro"
                        data-provide="datepicker" data-date-format="dd/mm/yyyy" data-date-language="pt-BR"
                        data-date-autoclose="true" data-date-today-highlight="true" data-date-orientation="auto"
                        placeholder="Ex.: dd/mm/aaaa" data-mask="00/00/0000" maxlength="10" />
                </div>
            </div>
            <div class="form-group">
                <label for="ddlSituacao">Situação</label>
                <select class="form-control col-sm-2" id="ddlSituacao" name="status">
                    <option th:each="status : ${todosStatusUsuario}" th:value="${status}" th:text="${status.descricao}"></option>
                </select>
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-primary col-sm-1">Salvar</button>
                <button type="button" onClick="javascript:history.back()" class="btn btn-secondary col-sm-1">Cancelar</button>
            </div>
        </div>
    </form>
</section>
</html>

Controller

@Controller
@RequestMapping("/usuario")
public class UsuarioController {
        
    private static final String USUARIO_LISTA = "UsuarioLista";
    private static final String REDIRECT_USUARIO_LISTA = "redirect:/usuario";
    private static final String USUARIO_ACAO = "UsuarioAcao";
    private static final String REDIRECT_USUARIO_ACAO = "redirect:/usuario/novo";
    
    @Autowired UsuarioServices usuarioServices;
    
    @RequestMapping("/novo")
    public ModelAndView novo() {
        ModelAndView mv = new ModelAndView(USUARIO_ACAO);
        mv.addObject("todosStatusUsuario", StatusUsuario.values());
        mv.addObject(new Usuario());
        return mv;
    }
    
    @RequestMapping(value = "/salvarUsuario", method = RequestMethod.POST)
    public String salvar(@ModelAttribute("form") @Validated Usuario usuario, Errors erros, RedirectAttributes attributes) {
        
        if(erros.hasErrors()) {
            Usuario form = new Usuario();
            BeanUtils.copyProperties(form, usuario);
            return USUARIO_ACAO;
        }
        
        if(usuario.getId_Usuario() != null) {
            if(usuarioServices.usuarioExiste(usuario)) {
                attributes.addFlashAttribute("classe", "alert alert-warning");
                attributes.addFlashAttribute("mensagem", "Usuário já existe!");
                attributes.addFlashAttribute("usuario", usuario.getUsuario());
                attributes.addFlashAttribute("senha", usuario.getSenha());
                attributes.addFlashAttribute("email", usuario.getEmail());
                return REDIRECT_USUARIO_ACAO;
            }
        }
        
        try {
            usuarioServices.salvarUsuario(usuario);
            attributes.addFlashAttribute("classe", "alert alert-success");
            attributes.addFlashAttribute("mensagem", "Usuário salvo com sucesso!");
        } catch (Exception ex) {
            attributes.addFlashAttribute("classe", "alert alert-danger");
            attributes.addFlashAttribute("mensagem", ex.getMessage());
        }
        return REDIRECT_USUARIO_ACAO;
    }
    
    @RequestMapping(value = "{codigo}")
    public ModelAndView editar(@PathVariable Long codigo) {
        ModelAndView mv = new ModelAndView(USUARIO_ACAO);
        Usuario usuario = usuarioServices.buscaPorId(codigo);
        mv.addObject(usuario);
        mv.addObject("action", "editar");
        return mv;
    }
    
    @RequestMapping(value = "editar/{codigo}", method = RequestMethod.PUT)
    public ModelAndView editarUsuario(@ModelAttribute("form") @Validated Usuario usuario, @PathVariable Long codigo) {
        ModelAndView mv = new ModelAndView(USUARIO_LISTA);
        usuarioServices.editarPorUsuario(usuario, codigo);
        return mv;
    }
        
}

Usuarioservices:

package com.SystemsSolutions.WebControl.service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.SystemsSolutions.WebControl.model.Perfil;
import com.SystemsSolutions.WebControl.model.Usuario;
import com.SystemsSolutions.WebControl.repository.UsuarioRepository;

@Service
public class UsuarioServices implements UserDetailsService{
    
    @Autowired
    private UsuarioRepository repository;
    
    //salva novo usuário
    public void salvarUsuario(Usuario usuario) {
        try {
            Date data = new Date(System.currentTimeMillis());
            usuario.setSenha(new BCryptPasswordEncoder().encode(usuario.getSenha()));
            usuario.setDataAlteracao(data); //GET DATA
            usuario.setHoraAlteracao(data); //GET HORA
            repository.save(usuario);
        } catch (DataIntegrityViolationException ex) {
            throw new IllegalArgumentException(ex.getMessage());
        }
        
    }
    
    public Usuario buscaPorId(Long id) {
        Optional<Usuario> lista = repository.findById(id);
        if(!lista.isEmpty())
            return lista.get();
        return null;
    }
    
    @Transactional()
    public void editarPorUsuario(Usuario usuario, Long id) {
        Date data = new Date(System.currentTimeMillis());
        usuario.setId_Usuario(id);
        usuario.setSenha(new BCryptPasswordEncoder().encode(usuario.getSenha()));
        usuario.setDataAlteracao(data); //GET DATA
        usuario.setHoraAlteracao(data); //GET HORA
        repository.EditByUsuario(
                usuario.getUsuario()
                , usuario.getSenha()
                , usuario.getEmail()
                , usuario.getDataAlteracao()
                , usuario.getHoraAlteracao()
                , usuario.getDataCadastro()
                , usuario.getStatus()
                , id);
    }
    
    //busca usuário por usuário no banco de dados
    @Transactional(readOnly = true)
    public Usuario buscarPorUsuario(String usuario) {
        return repository.findByUsuario(usuario);
    }
    
    //busca usuário por email no banco de dados
    public Usuario buscarPorEmail(String email) {
        return repository.findByEmail(email);
    }
    
    //busca todos os usuários
    public List<Usuario> buscarTodos(){
        return repository.findAll();
    }
    
    public void deletar(Long id) {
        repository.deleteById(id);
    }
    
    //autenticação de usuário (spring-security)
    @Override @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String user) throws UsernameNotFoundException {
        Usuario usuario = buscarPorUsuario(user);
        System.out.println("Usuário encontrado: " + usuario.getUsuario()
                        +  "\nSenha: " + usuario.getSenha()
                        +  "\nStatus: " + usuario.getStatus());
        
        if(usuario.getStatus().toString().equals("BLOQUEADO") || usuario.getStatus().toString().equals("PENDENTE")) {
            usuario = null;
        }
        
        return new User(
                usuario.getUsuario(),
                usuario.getSenha(),
                AuthorityUtils.createAuthorityList(getAuthorities(usuario.getPerfis()))
        );
    }
    //converte lista de perfis para array string
    private String[] getAuthorities(List<Perfil> perfis) {
        String[] authorities = new String[perfis.size()];
        
        for (int i = 0; i < perfis.size(); i++) {
            authorities[i] = perfis.get(i).getDesc();
        }
        return authorities;
    }
}

Usuariorepository

package com.SystemsSolutions.WebControl.repository;

import java.util.Date;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import com.SystemsSolutions.WebControl.model.StatusUsuario;
import com.SystemsSolutions.WebControl.model.Usuario;

public interface UsuarioRepository extends JpaRepository<Usuario, Long> {
    //From deve ser identico ao nome da classe, tal classe deve estar mapeada como Entity
    //nome da coluna deve ser identico ao nome do atributo da classe
    @Query("SELECT u FROM Usuario u WHERE u.usuario = :usuarioParam")
    Usuario findByUsuario(@Param("usuarioParam") String usuario);
    
    @Query("SELECT u FROM Usuario u WHERE u.email = :emailParam")
    Usuario findByEmail(@Param("emailParam") String email);
    
    @Modifying
    @Query("UPDATE Usuario u "
            + "SET u.usuario        = :usuarioParam"
            + ", u.senha            = :senhaParam"
            + ", u.email            = :emailParam"
            + ", u.dataAlteracao    = :dataAltParam"
            + ", u.horaAlteracao    = :horaAltParam"
            + ", u.dataCadastro     = :dataCadParam"
            + ", u.status           = :statusParam "
            + "WHERE u.id_usuario = :idParam")
    Void EditByUsuario(@Param("usuarioParam") String usuario
                        , @Param("senhaParam") String senha
                        , @Param("emailParam") String email
                        , @Param("dataAltParam") Date dataAlteracao
                        , @Param("horaAltParam") Date horaAlteracao
                        , @Param("dataCadParam") Date dataCadastro
                        , @Param("statusParam") StatusUsuario status
                    , @Param("idParam")Long id);
    
}

ERROR

2021-02-17 17:18:50.982 DEBUG 11504 --- [nio-8081-exec-8] o.s.web.servlet.DispatcherServlet        : PUT "/usuario/editar/8", parameters={masked}
2021-02-17 17:18:50.982 DEBUG 11504 --- [nio-8081-exec-8] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.SystemsSolutions.WebControl.controller.UsuarioController#editarUsuario(Usuario, Long)
2021-02-17 17:18:51.085 DEBUG 11504 --- [nio-8081-exec-8] org.hibernate.SQL                        : update usuario set usuario=?, senha=?, email=?, data_alteracao=?, hora_alteracao=?, data_cadastro=?, status=? where id_usuario=?
Hibernate: update usuario set usuario=?, senha=?, email=?, data_alteracao=?, hora_alteracao=?, data_cadastro=?, status=? where id_usuario=?
2021-02-17 17:18:51.085 TRACE 11504 --- [nio-8081-exec-8] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] - [EMERSON]
2021-02-17 17:18:51.086 TRACE 11504 --- [nio-8081-exec-8] o.h.type.descriptor.sql.BasicBinder      : binding parameter [2] as [VARCHAR] - [$2a$10$tUBTCwTcRTEJgjcHln8NGeVdD.b6kzayoqOF44UELVPRk6wd.v6nS]
2021-02-17 17:18:51.086 TRACE 11504 --- [nio-8081-exec-8] o.h.type.descriptor.sql.BasicBinder      : binding parameter [3] as [VARCHAR] - [[email protected]]
2021-02-17 17:18:51.086 TRACE 11504 --- [nio-8081-exec-8] o.h.type.descriptor.sql.BasicBinder      : binding parameter [4] as [DATE] - [Wed Feb 17 17:18:50 BRT 2021]
2021-02-17 17:18:51.086 TRACE 11504 --- [nio-8081-exec-8] o.h.type.descriptor.sql.BasicBinder      : binding parameter [5] as [TIME] - [Wed Feb 17 17:18:50 BRT 2021]
2021-02-17 17:18:51.086 TRACE 11504 --- [nio-8081-exec-8] o.h.type.descriptor.sql.BasicBinder      : binding parameter [6] as [DATE] - [Wed Feb 17 00:00:00 BRT 2021]
2021-02-17 17:18:51.086 TRACE 11504 --- [nio-8081-exec-8] o.h.type.descriptor.sql.BasicBinder      : binding parameter [7] as [VARCHAR] - [ATIVO]
2021-02-17 17:18:51.086 TRACE 11504 --- [nio-8081-exec-8] o.h.type.descriptor.sql.BasicBinder      : binding parameter [8] as [BIGINT] - [8]
2021-02-17 17:18:51.092 DEBUG 11504 --- [nio-8081-exec-8] o.s.web.servlet.DispatcherServlet        : Failed to complete request: java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Void (java.lang.Integer and java.lang.Void are in module java.base of loader 'bootstrap')
2021-02-17 17:18:51.096 ERROR 11504 --- [nio-8081-exec-8] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Void (java.lang.Integer and java.lang.Void are in module java.base of loader 'bootstrap')] with root cause

java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Void (java.lang.Integer and java.lang.Void are in module java.base of loader 'bootstrap')
    at com.sun.proxy.$Proxy456.EditByUsuario(Unknown Source) ~[na: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:564) ~[na:na]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:205) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at com.sun.proxy.$Proxy453.EditByUsuario(Unknown Source) ~[na:na]
    at com.SystemsSolutions.WebControl.service.UsuarioServices.editarPorUsuario(UsuarioServices.java:59) ~[classes/:na]
    at com.SystemsSolutions.WebControl.service.UsuarioServices$$FastClassBySpringCGLIB$$3ab2fb79.invoke(<generated>) ~[classes/:na]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367) ~[spring-tx-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118) ~[spring-tx-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at com.SystemsSolutions.WebControl.service.UsuarioServices$$EnhancerBySpringCGLIB$$772b0101.editarPorUsuario(<generated>) ~[classes/:na]
    at com.SystemsSolutions.WebControl.controller.UsuarioController.editarUsuario(UsuarioController.java:91) ~[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:564) ~[na:na]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:920) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:655) ~[tomcat-embed-core-9.0.37.jar:4.0.FR]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.37.jar:4.0.FR]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.37.jar:9.0.37]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:94) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) ~[na:na]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
    at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]

1 answer

2


In the following method:

Void EditByUsuario(@Param("usuarioParam") String usuario
                    , @Param("senhaParam") String senha
                    , @Param("emailParam") String email
                    , @Param("dataAltParam") Date dataAlteracao
                    , @Param("horaAltParam") Date horaAlteracao
                    , @Param("dataCadParam") Date dataCadastro
                    , @Param("statusParam") StatusUsuario status
                    , @Param("idParam") Long id);

The guy Void not supported. You were probably looking for the type void.

According to the spring data documentation, the function return can also be:

  • boolean: true if any lines have been changed, false otherwise; or
  • int: returns the number of lines changed.

In accordance with Appendix D to the Spring Data JPA Wrappers (e. g., Integerand Boolean) are also supported.

Spring Data is getting lost with the method signature with an unsupported return type. The implementation generated by the library is trying to convert a type Integer for the guy Void.

java.lang.Classcastexception: class java.lang.Integer cannot be cast to class java.lang.Void (java.lang.Integer and java.lang.Void are in module java.base of Loader 'bootstrap').

That said, once you’re using with the , the method editByUsuario and your update statement explicit in JPQL seem unnecessary to me. You can do the same thing with standard methods of JpaRepository.

@Transactional
public void editarPorUsuario(Usuario usuario, Long id) {
    // assumindo que usuario é detached
    // obtém uma referência para o usuário administrado pelo contexto de persistência
    Usuario managedUser = repository.getOne(id); 
    // Copia dados a serem atualizados
    Date data = new Date(System.currentTimeMillis());
    managedUser.setUsuario(usuario.getUsuario());
    managedUser.setSenha(new BCryptPasswordEncoder().encode(usuario.getSenha()));
    managedUser.setEmail(usuario.getEmail());
    // ... outros campos a serem atualizados
    managedUser.setDataAlteracao(data);
    managedUser.setHoraAlteracao(data); 

    /* Opcionalmente você pode chamar operações de save ou saveAndFlush
     * Mas veja que como você já tem uma transação aberta isso costuma ser
     * um anti-pattern: https://vladmihalcea.com/jpa-persist-and-merge/
     */
}

In fact, the other two methods of UsuarioRepository can also be simplified once Spring Data achieves derive the method name. It seems that you are already using the correct nomenclature for consult, o in both cases the use of @Query and @Param are unnecessary. However, this is outside the scope of the question.

  • It worked, I changed the return to Integer and it worked. thanks partner.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.