0

Bom dia a todos! Estou com problemas no relacionamento de entidades na api, o banco foi criado corretamente pelo Spring como pode ser visto abaixo:

Relacionamento ManyToMany na tabela viagem:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@ManyToMany(targetEntity = Passageiro.class)
@JoinTable(name="viagem_has_passageiros", joinColumns=
        {@JoinColumn(name="viagem_id")}, inverseJoinColumns=
        {@JoinColumn(name="passageiro_id")})
private List passageiros;

@ManyToMany(targetEntity = Motorista.class)
@JoinTable(name="viagem_has_motoristas", joinColumns=
        {@JoinColumn(name="viagem_id")}, inverseJoinColumns=
        {@JoinColumn(name="motorista_id")})
private List motoristas;

Estou focando em fazer funcionar primeiro os passageiros, então após inicializada a api, testo no postman: inserir a descrição da imagem aqui Testei tanto com "viagem_id" quanto sem, pois pensei que ele poderia incrementar direto. Ele insere a viagem normalmente se for sem os passageiros/motoristas, porém com eles, tanto como GET ou PUT, dá o seguinte erro:

"status": 500,
"error": "Internal Server Error",
"message": "Error accessing field [private int com.sambaonibus.samba_onibus.domain.Passageiro.id] by reflection for persistent property [com.sambaonibus.samba_onibus.domain.Passageiro#id] : {viagem_id=2, passageiro_id=1}; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private int com.sambaonibus.samba_onibus.domain.Passageiro.id] by reflection for persistent property [com.sambaonibus.samba_onibus.domain.Passageiro#id] : {viagem_id=2, passageiro_id=1}",
"trace": "org.springframework.orm.jpa.JpaSystemException: Error accessing field [private int com.sambaonibus.samba_onibus.domain.Passageiro.id] by reflection for persistent property [com.sambaonibus.samba_onibus.domain.Passageiro#id] : {viagem_id=2, passageiro_id=1}; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private int com.sambaonibus.samba_onibus.domain.Passageiro.id] by reflection for persistent property [com.sambaonibus.samba_onibus.domain.Passageiro#id] : {viagem_id=2, passageiro_id=1}\r\n\tat org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:351)\r\n\tat org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:253)\r\n\tat org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527)\r\n\tat org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)\r\n\tat org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)\r\n\tat org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)\r\n\tat org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:138)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)\r\n\tat org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)\r\n\tat org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)\r\n\tat org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)\r\n\tat com.sun.proxy.$Proxy107.save(Unknown Source)\r\n\tat com.sambaonibus.samba_onibus.controller.ViagensController.edit(ViagensController.java:56)\r\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.lang.reflect.Method.invoke(Method.java:498)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:919)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:663)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:741)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat com.sambaonibus.samba_onibus.cors.WebConfig.doFilter(WebConfig.java:34)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)\r\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)\r\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)\r\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)\r\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)\r\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)\r\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)\r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)\r\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)\r\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)\r\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)\r\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\r\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)\r\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)\r\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n\tat java.lang.Thread.run(Thread.java:748)\r\nCaused by: org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private int com.sambaonibus.samba_onibus.domain.Passageiro.id] by reflection for persistent property [com.sambaonibus.samba_onibus.domain.Passageiro#id] : {viagem_id=2, passageiro_id=1}\r\n\tat org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:75)\r\n\tat org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:224)\r\n\tat org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:4933)\r\n\tat org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:148)\r\n\tat org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:922)\r\n\tat org.hibernate.internal.SessionImpl.merge(SessionImpl.java:892)\r\n\tat org.hibernate.engine.spi.CascadingActions$6.cascade(CascadingActions.java:261)\r\n\tat org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:490)\r\n\tat org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:415)\r\n\tat org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:216)\r\n\tat org.hibernate.engine.internal.Cascade.cascadeCollectionElements(Cascade.java:523)\r\n\tat org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:455)\r\n\tat org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:418)\r\n\tat org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:216)\r\n\tat org.hibernate.engine.internal.Cascade.cascade(Cascade.java:149)\r\n\tat org.hibernate.event.internal.DefaultMergeEventListener.cascadeOnMerge(DefaultMergeEventListener.java:460)\r\n\tat org.hibernate.event.internal.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:326)\r\n\tat org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:170)\r\n\tat org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:69)\r\n\tat org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:900)\r\n\tat org.hibernate.internal.SessionImpl.merge(SessionImpl.java:886)\r\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.lang.reflect.Method.invoke(Method.java:498)\r\n\tat org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:350)\r\n\tat com.sun.proxy.$Proxy100.merge(Unknown Source)\r\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.lang.reflect.Method.invoke(Method.java:498)\r\n\tat org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:308)\r\n\tat com.sun.proxy.$Proxy100.merge(Unknown Source)\r\n\tat org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:492)\r\n\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.lang.reflect.Method.invoke(Method.java:498)\r\n\tat org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:359)\r\n\tat org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200)\r\n\tat org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:644)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)\r\n\tat org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:608)\r\n\tat org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595)\r\n\tat org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)\r\n\tat org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)\r\n\tat org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)\r\n\tat org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)\r\n\tat org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)\r\n\t... 67 more\r\nCaused by: java.lang.IllegalArgumentException: Can not set int field com.sambaonibus.samba_onibus.domain.Passageiro.id to java.util.LinkedHashMap\r\n\tat sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)\r\n\tat sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)\r\n\tat sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)\r\n\tat sun.reflect.UnsafeIntegerFieldAccessorImpl.getInt(UnsafeIntegerFieldAccessorImpl.java:56)\r\n\tat java.lang.reflect.Field.getInt(Field.java:574)\r\n\tat org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:62)\r\n\t... 118 more\r\n",
"path": "/viagens"

Quem já tiver passado por esse erro... ou tem alguma ideia, agradeço muito a ajuda!

1 Resposta 1

1

Olá.

Está um pouco difícil visualizar o erro pela mensagem de resposta do Postman e sem todas as classes entidades, mas vamos lá. Tente substituir o mapeamento do seu relacionamento para a seguinte forma:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@ManyToMany
@JoinTable(name = "viagem_has_passageiros",
          joinColumns = @JoinColumn(name="viagem_id"),
          inverseJoinColumns = @JoinColumn(name="passageiro_id")
)
private List<Passageiro> passageiros;

@ManyToMany
@JoinTable(name = "viagem_has_motoristas",
          joinColumns = @JoinColumn(name="viagem_id"),
          inverseJoinColumns = @JoinColumn(name="motorista_id")
)
private List<Motorista> motoristas;

Nas sua classe Passageiro:

@ManyToMany(mappedBy = "passageiros")
private List<Viagem> viagens;

Na sua classe Motorista:

@ManyToMany(mappedBy = "motoristas")
private List<Viagem> viagens;

Ah! E talvez vc tenha problemas com LazyException futuramente. Mas vamos vamos com calma.

5
  • Obrigado pela ajuda! Fazendo estas modificações obtive o seguinte erro: "status": 500, "error": "Internal Server Error", "message": "org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.sambaonibus.samba_onibus.domain.Passageiro; nested exception is java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.sambaonibus.samba_onibus.domain.Passageiro" Commented 7/06/2019 às 16:52
  • Blz. Vc precisa acrescentar o cascade agora, ficando assim: @ManyToMany(cascade = CascadeType.ALL)
    – Gustavo
    Commented 7/06/2019 às 16:59
  • "status": 500, "error": "Internal Server Error", "message": "Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction", Commented 7/06/2019 às 17:05
  • Estou procurando aqui, parece que falta uma anotação @Transaction Commented 7/06/2019 às 17:05
  • Acredito que ai o problema não é relacionado ao mapeamento. Isso significa que está dando algum erro na hora de fazer alterações no BD. Edita a sua pergunta colocando as classes que vc está utilizando as funções da JPA por favor e as outras classes de entidades. Procure no log de erro tbm o pq desse erro (O último Caused by seria um bom começo)
    – Gustavo
    Commented 7/06/2019 às 17:43

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .