保留新元素时发生唯一索引或主键冲突

时间:2019-03-17 03:17:08

标签: java spring hibernate jpa

我正在创建一个应用程序,并且在保存新项目时出现以下错误:

2019-03-17 00:05:09 WARN  o.h.e.jdbc.spi.SqlExceptionHelper - SQL Error: 23505, SQLState: 23505
2019-03-17 00:05:09 ERROR o.h.e.jdbc.spi.SqlExceptionHelper - Unique index or primary key violation: "PUBLIC.PRIMARY_KEY_3 ON PUBLIC.LOJA_DOCUMENTO(ID_DOCUMENTO) VALUES 1"; SQL statement:
/* insert br.com.odin.loja.backend.model.Documento */ insert into loja_documento (codigo_documento, descricao_documento, id_pessoa, valor_documento, id_documento) values (?, ?, ?, ?, ?) [23505-198]
2019-03-17 00:05:09 ERROR o.h.i.ExceptionMapperStandardImpl - HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
2019-03-17 00:05:09 ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint ["PUBLIC.PRIMARY_KEY_3 ON PUBLIC.LOJA_DOCUMENTO(ID_DOCUMENTO) VALUES 1"; SQL statement:
/* insert br.com.odin.loja.backend.model.Documento */ insert into loja_documento (codigo_documento, descricao_documento, id_pessoa, valor_documento, id_documento) values (?, ?, ?, ?, ?) [23505-198]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Unique index or primary key violation: "PUBLIC.PRIMARY_KEY_3 ON PUBLIC.LOJA_DOCUMENTO(ID_DOCUMENTO) VALUES 1"; SQL statement:
/* insert br.com.odin.loja.backend.model.Documento */ insert into loja_documento (codigo_documento, descricao_documento, id_pessoa, valor_documento, id_documento) values (?, ?, ?, ?, ?) [23505-198]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:457) ~[h2-1.4.198.jar:1.4.198]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:427) ~[h2-1.4.198.jar:1.4.198]
    at org.h2.message.DbException.get(DbException.java:205) ~[h2-1.4.198.jar:1.4.198]
    at org.h2.message.DbException.get(DbException.java:181) ~[h2-1.4.198.jar:1.4.198]
    at org.h2.index.BaseIndex.getDuplicateKeyException(BaseIndex.java:103) ~[h2-1.4.198.jar:1.4.198]
    at org.h2.mvstore.db.MVSecondaryIndex.checkUnique(MVSecondaryIndex.java:220) ~[h2-1.4.198.jar:1.4.198]
    at org.h2.mvstore.db.MVSecondaryIndex.add(MVSecondaryIndex.java:196) ~[h2-1.4.198.jar:1.4.198]
    at org.h2.mvstore.db.MVTable.addRow(MVTable.java:703) ~[h2-1.4.198.jar:1.4.198]
    at org.h2.command.dml.Insert.insertRows(Insert.java:180) ~[h2-1.4.198.jar:1.4.198]
    at org.h2.command.dml.Insert.update(Insert.java:132) ~[h2-1.4.198.jar:1.4.198]
    at org.h2.command.CommandContainer.update(CommandContainer.java:133) ~[h2-1.4.198.jar:1.4.198]
    at org.h2.command.Command.executeUpdate(Command.java:267) ~[h2-1.4.198.jar:1.4.198]
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:200) ~[h2-1.4.198.jar:1.4.198]
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:154) ~[h2-1.4.198.jar:1.4.198]
    at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61) ~[HikariCP-3.2.0.jar:na]
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java) ~[HikariCP-3.2.0.jar:na]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3171) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3686) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:90) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:478) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:356) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1454) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:511) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3283) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2479) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:473) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:178) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:39) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:271) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:98) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:532) ~[spring-orm-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:746) ~[spring-tx-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:714) ~[spring-tx-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:533) ~[spring-tx-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:304) ~[spring-tx-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at br.com.odin.loja.backend.service.DocumentoService$$EnhancerBySpringCGLIB$$25558288.save(<generated>) ~[classes/:na]
    at br.com.odin.loja.backend.controller.DocumentoController.save(DocumentoController.java:43) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_201]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_201]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_201]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_201]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200) ~[tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_201]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_201]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_201]

我的模型类Documento.Java

package br.com.odin.loja.backend.model;

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;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@Entity
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@Table(name = "loja_documento")
public class Documento {

    // Attributes
    @Id
    @Column(name = "ID_DOCUMENTO", nullable = false, precision = 3, scale = 0)
    @GeneratedValue(generator = "seq_generator", strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name="seq_generator", sequenceName = "SEQ_LOJA_DOCUMENTO", allocationSize=1)
    private Integer id;

    @Column(name = "CODIGO_DOCUMENTO", nullable = false, length = 25)
    private String codigo;

    @Column(name = "DESCRICAO_DOCUMENTO", nullable = false, length = 25)
    private String descricao;

    @Column(name = "VALOR_DOCUMENTO", nullable = false, length = 25)
    private String valor;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "ID_PESSOA")
    @JsonIgnoreProperties(value = "documentos", allowSetters = true)
    private Pessoa pessoa;

    // Constructors

    // Getters & Setters
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCodigo() {
        return codigo;
    }

    public void setCodigo(String codigo) {
        this.codigo = codigo;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public String getValor() {
        return valor;
    }

    public void setValor(String valor) {
        this.valor = valor;
    }

    public Pessoa getPessoa() {
        return pessoa;
    }

    public void setPessoa(Pessoa pessoa) {
        this.pessoa = pessoa;
    }

    // Methods

}

我的存储库DocumentoRepository.Java

package br.com.odin.loja.backend.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import br.com.odin.loja.backend.model.Documento;
import br.com.odin.loja.backend.model.Pessoa;

@Repository
public class DocumentoRepository {

    // Attributes
    @Autowired
    private EntityManager entityManager;

    // Methods
    public Documento save(Documento documento) {
        entityManager.persist(documento);
        return documento;
    }

    public List<Documento> findAll() {
        return entityManager.createQuery("from Documento").getResultList();
    }

    public Documento findById(Integer id) {
        return entityManager.find(Documento.class, id);
    }

    public List<Documento> findByTipo(String tipoSearch) {

        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<Documento> criteriaQuery = criteriaBuilder.createQuery(Documento.class);
        Root<Documento> documento = criteriaQuery.from(Documento.class);
        TypedQuery<Documento> typedQuery;

        criteriaQuery.where(
                criteriaBuilder.like(
                        documento.<String>get("codigo"), "%" + tipoSearch + "%"));

        typedQuery = entityManager.createQuery(criteriaQuery);

        return typedQuery.getResultList();
    }

    public Boolean removeById(Integer id) {
        Documento documento = this.findById(id);

        try {
            entityManager.remove(documento);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public Documento update(Documento documento) {
        return entityManager.merge(documento);
    }
}

我的服务DocumentoService.Java

package br.com.odin.loja.backend.service;

import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import br.com.odin.loja.backend.exception.DocumentoInvalidoException;
import br.com.odin.loja.backend.model.Documento;
import br.com.odin.loja.backend.model.Pessoa;
import br.com.odin.loja.backend.repository.DocumentoRepository;

@Service                // Expoe a classe como um serviço do spring 
@Transactional          // Marca a classe com gerenciamento de transações (SPRING)
public class DocumentoService {

    // Attributes
    @Autowired
    private DocumentoRepository documentoRepository;

    @Autowired
    private PessoaService pessoaService;

    // General Methods
    private void validateRg(String rg) throws DocumentoInvalidoException {

        if (rg.length() < 9) {
            throw new DocumentoInvalidoException("Número de caracteres inválidos! Favor verificar.");
        }

        if (rg.contains("-") || rg.contains(".")) {
            throw new DocumentoInvalidoException("Digite o CPF sem pontuação ou traço! Favor verificar.");
        }

        if (rg.length() > 9) {
            throw new DocumentoInvalidoException("Número de caracteres inválidos! Favor verificar.");
        }
    }

    private void validateCpf(String cpf) throws DocumentoInvalidoException {

        if (cpf.length() < 11) {
            throw new DocumentoInvalidoException("Número de caracteres inválidos! Favor verificar.");
        }

        if (cpf.contains("-") || cpf.contains(".")) {
            throw new DocumentoInvalidoException("Digite o CPF sem pontuação ou traço! Favor verificar.");
        }

        if (cpf.length() > 11) {
            throw new DocumentoInvalidoException("Número de caracteres inválidos! Favor verificar.");
        }
    }


    public String getFilterProperty(String filter) {
        if (filter != null) {
            return filter.substring(0, filter.indexOf("="));    
        }
        return "default";
    }

    public String getFilterValue(String filter) {
        return filter.substring(filter.indexOf("=") + 1, filter.length());
    }

    // API Methods
    public List<Documento> find(String filter){

        switch (getFilterProperty(filter)) {

            case "tipo":
                return findByTipo(getFilterValue(filter));

            case "id":
                Documento documentoResult = findById(Integer.parseInt(getFilterValue(filter)));
                List<Documento> listDocumento = new ArrayList<Documento>();
                listDocumento.add(documentoResult);
                return listDocumento;

            default:
                return findAll();       
        }
    }

    public Documento findById(Integer id) {
        return documentoRepository.findById(id);
    }

    public List<Documento> findByTipo(String tipoSearch) {
        return documentoRepository.findByTipo(tipoSearch);
    }

    public List<Documento> findAll() {
        return documentoRepository.findAll();
    }

    public Documento save(Documento documento) throws DocumentoInvalidoException{
        try {

            if (documento.getCodigo().equals("RG")) {
                validateRg(documento.getValor());   
            } 

            if (documento.getCodigo().equals("CPF")) {
                validateCpf(documento.getValor());
            }

            Pessoa pessoa = pessoaService.findById(documento.getPessoa().getId());
            pessoa.setDocumentos(null);
            documento.getPessoa().setId(pessoa.getId());
            return documentoRepository.save(documento);
        } catch (DocumentoInvalidoException exception) {
            System.out.println("Error message: " + exception.getMessage());
            throw new DocumentoInvalidoException(exception.getMessage());
        }
    }

    public Boolean removeById(Integer id) {
        return documentoRepository.removeById(id);
    }

    public Documento update(Documento documentoAlterado, Integer id) {
        documentoAlterado.setId(id);
        return documentoRepository.update(documentoAlterado);
    }

}

我的控制器DocumentoController.Java

package br.com.odin.loja.backend.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import br.com.odin.loja.backend.exception.DocumentoInvalidoException;
import br.com.odin.loja.backend.model.Documento;
import br.com.odin.loja.backend.model.Pessoa;
import br.com.odin.loja.backend.service.DocumentoService;
import br.com.odin.loja.backend.service.PessoaService;

@RestController
@RequestMapping("/documentos")
public class DocumentoController {

    //Attributes
    @Autowired
    private DocumentoService documentoService;

    // API Methods
    @GetMapping("")
    public List<Documento> find(@RequestParam(value="filter", required = false) String filter) {
        List<Documento> documentoList = documentoService.find(filter);

        for(int i = 0; i < documentoList.size(); i++) {
            documentoList.get(i).getPessoa().setDocumentos(null);   
        }
        return documentoList;
    }

    @PostMapping("/novo")
    public Documento save(@RequestBody Documento documento) throws DocumentoInvalidoException {
        return documentoService.save(documento);
    }

    @GetMapping("/{id}")
    public Documento findById(@PathVariable("id") Integer id) {
        return documentoService.findById(id);
    }

    @DeleteMapping("/{id}/remover")
    public Boolean remove(@PathVariable("id") Integer id) {
        return documentoService.removeById(id);
    }

    @PutMapping("/{id}/alterar")
    public Documento update (@PathVariable("id") Integer id, @RequestBody Documento documento) {
        return documentoService.update(documento, id);
    }

}

我正在使用h2数据库,并将一些数据保存在数据库中

db.sql

-- Pessoas

INSERT INTO LOJA_PESSOA (id_pessoa, nome_pessoa) VALUES (1, 'Teste 1');
INSERT INTO LOJA_PESSOA (id_pessoa, nome_pessoa) VALUES (2, 'Teste 2');
INSERT INTO LOJA_PESSOA (id_pessoa, nome_pessoa) VALUES (3, 'Teste 3');

-- Documentos

INSERT INTO LOJA_DOCUMENTO (id_documento, codigo_documento, descricao_documento, valor_documento, id_pessoa) VALUES (1, 'CPF', 'CPF', '99988877766', 1);
INSERT INTO LOJA_DOCUMENTO (id_documento, codigo_documento, descricao_documento, valor_documento, id_pessoa) VALUES (2, 'RG', 'RG', '998887776', 1);
INSERT INTO LOJA_DOCUMENTO (id_documento, codigo_documento, descricao_documento, valor_documento, id_pessoa) VALUES (3, 'CPF', 'CPF', '11122233344', 2);
INSERT INTO LOJA_DOCUMENTO (id_documento, codigo_documento, descricao_documento, valor_documento, id_pessoa) VALUES (4, 'RG', 'RG', '112223334', 2);
INSERT INTO LOJA_DOCUMENTO (id_documento, codigo_documento, descricao_documento, valor_documento, id_pessoa) VALUES (5, 'CPF', 'CPF', '98765432199', 3);
INSERT INTO LOJA_DOCUMENTO (id_documento, codigo_documento, descricao_documento, valor_documento, id_pessoa) VALUES (6, 'RG', 'RG', '987654321', 3);

更新

当我阅读注释并分析我的data.sql时,我通过更改sql日期以使其使用数据库生成的顺序来解决了该问题。 新的data.sql:

INSERT INTO LOJA_DOCUMENTO (id_documento, codigo_documento, descricao_documento, valor_documento, id_pessoa) VALUES (SEQ_LOJA_DOCUMENTO.nextval, 'CPF', 'CPF', '99988877766', 1);
INSERT INTO LOJA_DOCUMENTO (id_documento, codigo_documento, descricao_documento, valor_documento, id_pessoa) VALUES (SEQ_LOJA_DOCUMENTO.nextval, 'RG', 'RG', '998887776', 1);
INSERT INTO LOJA_DOCUMENTO (id_documento, codigo_documento, descricao_documento, valor_documento, id_pessoa) VALUES (SEQ_LOJA_DOCUMENTO.nextval, 'CPF', 'CPF', '11122233344', 2);
INSERT INTO LOJA_DOCUMENTO (id_documento, codigo_documento, descricao_documento, valor_documento, id_pessoa) VALUES (SEQ_LOJA_DOCUMENTO.nextval, 'RG', 'RG', '112223334', 2);
INSERT INTO LOJA_DOCUMENTO (id_documento, codigo_documento, descricao_documento, valor_documento, id_pessoa) VALUES (SEQ_LOJA_DOCUMENTO.nextval, 'CPF', 'CPF', '98765432199', 3);
INSERT INTO LOJA_DOCUMENTO (id_documento, codigo_documento, descricao_documento, valor_documento, id_pessoa) VALUES (SEQ_LOJA_DOCUMENTO.nextval, 'RG', 'RG', '987654321', 3);

0 个答案:

没有答案