Столбец не может быть нулевым во многих отношениях при добавлении - PullRequest
0 голосов
/ 25 января 2019

У меня есть 2 таблицы Products и Entrepot (Warehouse), и они имеют много-много отношений.Когда я пытаюсь добавить новый продукт в массив entrepotProducts и сохранить экземпляр entropot, я получаю, что product_id не может быть нулевым

Enrepot.java

@Entity(name= "Entrepot")
@Table(name = "entrepot")
@Data
@ToString(exclude = "EntrepotProduct")
@EqualsAndHashCode(exclude = "entrepotProduct")
@RequiredArgsConstructor
@NoArgsConstructor
public class Entrepot {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;


private @NonNull String name;


private @NonNull String address;


private @NonNull Integer capacite;

private boolean etat;

@OneToMany(
        mappedBy = "entrepot",
        cascade = CascadeType.ALL,
        orphanRemoval = true
)
private List<EntrepotProduct> entrepotProducts= new ArrayList<>();

@Column(nullable = false, updatable = false)
@CreationTimestamp
private Date createdAt;

public void removeProduct(Product p) {
    for (Iterator<EntrepotProduct> iterator = entrepotProducts.iterator();
         iterator.hasNext(); ) {
        EntrepotProduct ep = iterator.next();

        if (ep.getEntrepot().equals(this) && ep.getProduct().equals(p)) {
            iterator.remove();
            ep.getProduct().getEntrepotProducts().remove(ep);
            ep.setEntrepot(null);
            ep.setProduct(null);
        }
    }
}

Product.java

@Entity(name= "Product")
@Table(name = "product")
@Data
@ToString(exclude = "EntrepotProduct")
@EqualsAndHashCode(exclude = "entrepotProduct")
@RequiredArgsConstructor
@NoArgsConstructor
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;


private @NonNull String name;

private @NonNull float volume;

private @NonNull int quantite;

private @NonNull float price;

@OneToMany(
        mappedBy = "product",
        cascade = CascadeType.ALL,
        orphanRemoval = true
)
private List<EntrepotProduct> entrepotProducts= new ArrayList<>();

@Column(nullable = false, updatable = false)
@CreationTimestamp
private Date createdAt;

}

EntrepotProduct.java

@Entity

@Getter
@Setter
@NoArgsConstructor
@RequiredArgsConstructor
public class EntrepotProduct implements Serializable{

@Id
@ManyToOne
@JoinColumn(name = "product_id")
private Product product;

@Id
@ManyToOne
@JoinColumn(name = "entrepot_id")
private Entrepot entrepot;

private @NonNull Integer capacite;

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass())
        return false;

    EntrepotProduct that = (EntrepotProduct) o;
    return Objects.equals(product.getId(), that.product.getId()) &&
           Objects.equals(entrepot.getId(), that.entrepot.getId());
}

@Override
public int hashCode() {
    return Objects.hash(product.getId(), entrepot.getId());
}
}

Контроллер:

ЭТОТ КОД РАБОТАЕТ:

    Entrepot en1 = new Entrepot("E","Essaouira",100);
    entrepotRepository.save(en1);
    log.info(en1.toString());

    Entrepot en2 = new Entrepot("E","Jdida",777);
    entrepotRepository.save(en2);
    log.info(en2.toString());

    Product p = new Product("P100",987,22,777);
    p.getEntrepotProduct().add(new EntrepotProduct(p, en1, 888));
    p.getEntrepotProduct().add(new EntrepotProduct(p, en2, 666));
    productRepository.save(p);

ЭТО НЕ РАБОТАЕТ:

    Entrepot en1 = entrepotRepository.findById(4).get();
    entrepotRepository.save(en1);
    log.info(en1.toString()); // it is not null

    Entrepot en2 = entrepotRepository.findById(7).get();
    entrepotRepository.save(en2);
    log.info(en2.toString()); // it is not null

    Product p = new Product("P100",987,22,777);
    p.getEntrepotProduct().add(new EntrepotProduct(p, en1, 888));
    p.getEntrepotProduct().add(new EntrepotProduct(p, en2, 666));
    productRepository.save(p);

java.sql.SQLIntegrityConstraintViolationException: столбец product_id не может иметь значение null в com.mysql.cj.jdbc.exceptions.SQLError.createSQLException (SQLError.java:117) ~ [mysql-connector-java-8.0.13.jar: 8.0.13] в com.mysql.cj.jdbc.exceptions.SQLError.createSQLException (SQLError.java:97) ~[mysql-connector-java-8.0.13.jar: 8.0.13] в com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException (SQLExceptionsMapping.java:122) ~ [mysql-connector-java-8.0.13.jar: 8.0.13] at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal (ClientPreparedStatement.java:974) ~ [mysql-connector-java-8.0.13.jar:8.0.13] в com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal (ClientPreparedStatement.java:1113) ~ [mysql-connector-java-8.0.13.jar: 8.0.13] в com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal (ClientPreparedStatement.java:1061) ~ [mysql -nector-java-8.0.13.jar: 8.0.13] по адресу com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate (Client ~rejS): клиентский_представить-connector-java-8.0.13.jar: 8.0.13] at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate (ClientPreparedStatement.java:1046) ~ [mysql-connector-java-8.0.13.jar: 8.0.13] в com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate (ProxyPreparedStatement.java:61) ~ [HikariCP-3.2.0.jar: na] в com.zaxxer.hikari.pool.HikariProxyPreparedStatement.exrejikProtate ()~ [HikariCP-3.2.0.jar: na] в org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate (ResultSetReturnImpl.java:175) ~ [hibernate-core-5.3.7.Final.jar: 5.3.7.Final] в org.hibernate.persister.entity.AbstractEntityPersister.insert (AbstractEntityPersister.java:3171) ~ [hibernate-core-5.3.7.Final.jar: 5.3.7.Final] в org.hibernate.persister.entity.AbstractEntityPersister.insert (AbstractEntityPersister.java:3686) ~ [hibernate-core-5.3.7.Final.jar: 5.3.7.Final] в org.hibernate.action.internal.EntityInsertAction.execute (EntityInsertAction.java:90) ~ [hibernate-core-5.3.7.Final.jar: 5.3.7.Final] в org.hibernate.engine.spi.ActionQueue.executeActions (ActionQueue.java:604) ~ [hibernate-core-5.3.7.Final.jar: 5.3.7.Final] вorg.hibernate.engine.spi.ActionQueue.executeActions (ActionQueue.java:478) ~ [hibernate-core-5.3.7.Final.jar: 5.3.7.Final] в org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:356) ~ [hibernate-core-5.3.7.Final.jar: 5.3.7.Final] в org.hibernate.event.internal.DefaultFlushEventListener.onFlush (DefaultFlushEventListener.java:39) ~ [hibernate-core-5.3.7.Final.jar: 5.3.7.Final] в org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1454) ~ [hibernate-core-5.3.7.Final.jar: 5.3.7.Final] в org.hibernate.internal.SessionImpl.managedFlush (SessionImpl.java:511) ~ [hibernate-core-5.3.7.Final.jar: 5.3.7.Final] в org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion (SessionImpl.java:3283) ~ [hibernate-core-5.3.7.Final.jar: 5.3.7.Final] в org.hibernate.internal.SessionImpl.beforeTransactionCompletion (SessionImpl.java:2479) ~ [hibernate-core-5.3.7.Final.jar: 5.3.7.Final] в 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. в org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access $ 300 (JdbcResourceLocalTransactionCoordinatorImpl.java:39) ~ [hibernate-core-5.3.7.Final.jar]: 5.3.7 at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl $ TransactionDriverControlImpl.commit (JdbcResourceLocalTransactionCoordinatorImpl.java:271) ~ [hibernate-core-5.3.ar. в org.hibernate.engine.transaction.internal.TransactionImpl.commit (TransactionImpl.java:98) ~ [hibernate-core-5.3.7.Final.jar: 5.3.7.Final] в org.springframework.orm.jpa.JpaTransactionManager.doCommit (JpaTransactionManager.java:532) ~ [spring-orm-5.1.4.RELEASE.jar: 5.1.4.RELEASE] at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit (AbstractPlatformTransactionManager.java:746) ~ [spring-tx-5.1.4.RELEASE.jar: 5.1.4.RELEASE] at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit (AbstractPlatformTransactionManager.java:714) ~ [spring-tx-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning (TransactionAspectSupport.java:533) ~ [spring-tx-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction (TransactionAspectSupport.java:304) ~ [spring-tx-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в org.springframework.transaction.interceptor.TransactionInterceptor.invoke (TransactionInterceptor.java:98) ~ [spring-tx-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (ReflectiveMethodInvocation.java:186) ~ [spring-aop-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke (PersistenceExceptionTranslationInterceptor.java:139) ~ [spring-tx-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (ReflectiveMethodInvocation.java:186) ~ [spring-aop-5.1.4.RELEASE.jar: 5.1.4.RELEASE] at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor $ CrudMethodMetadataPopulationMethodInterceptor.invoke (CrudMethodMetadataPostProcessor.java:1EL. data.j. 2.1.E.J.E.1.E 2.1.E.E.E.1.E. в org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (ReflectiveMethodInvocation.java:186) ~ [spring-aop-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke (ExposeInvocationInterceptor.java:93) ~ [spring-aop-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (ReflectiveMethodInvocation.java:186) ~ [spring-aop-5.1.4.RELEASE.jar: 5.1.4.RELEASE] at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke (SurroundingTransactionDetectorMethodInterceptor.java:61) ~ [spring-data-commons-2.1.4.RELEASE.jELE: 2.1.4.Re] в org.springframework.aop.framework.ReflectiveMethodInvocation.proceed (ReflectiveMethodInvocation.java:186) ~ [spring-aop-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в org.springframework.aop.framework.JdkDynamicAopProxy.invoke (JdkDynamicAopProxy.java:212) ~ [spring-aop-5.1.4.RELEASE.jar: 5.1.4.RELEASE] на com.sun.proxy. $ Proxy140.save (Неизвестный источник) ~ [na: na] в com.example.demo.controller.Controller.addEntToProd (Controller.java:90) ~ [classes /: na] at sun.reflect.NativeMethodAccessorImpl.invoke0 (собственный метод) ~ [na: 1.8.0_192-ea]at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) ~ [na: 1.8.0_192-ea] at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl_2. 1.8a: ja: 1.8: e)в java.lang.reflect.Method.invoke (Method.java:498) ~ [na: 1.8.0_192-ea] в org.springframework.web.method.support.InvocableHandlerMethod.doInvoke (InvocableHandlerMethod.java:18)spring-web-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest (InvocableHandlerMethod.java:138) ~ [spring-web-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle (ServletInvocableHandlerMethod.java:102) ~ [spring-webmREE-5.1.jpg4.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod (RequestMappingHandlerAdapter.java:895) ~ [spring-webmvc-5.1.4.RELEASE.jELE: 5.1.4]org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal (RequestMappingHandlerAdapter.java:800) ~ [spring-webmvc-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в org.springframework.webserv.mvc.method.AbstractHandlerMethodAdapter.handle (AbstractHandlerMethodAdapter.java:87) ~ [spring-webmvc-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в org.springframework.web.servlet.DispatcherServlet.Servlet.java: 1038) ~ [spring-webmvc-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в org.springframework.web.servlet.DispatcherServlet.doService (DispatcherServlet.java:942) ~ [spring-webmvc-5.1.4.RELEASE.jar: 5.1.4.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest (FrameworkServlet.java:1005) ~ [spring-webmvc-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в org.springframework.web.servlet.FrameworkServlet.doPost (FrameworkServlet.java:908) ~ [spring-webmvc-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в javax.servlet.http.HttpServlet.служба (HttpServlet.java:660) ~ [tomcat-embed-core-9.0.14.jar: 9.0.14]в org.springframework.web.servlet.FrameworkServlet.service (FrameworkServlet.java:882) ~ [spring-webmvc-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в javax.servlet.http.HttpServlet.service (HttpServlet.java:741) ~ [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:231) ~ [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain.java:166) ~ [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.tomcat.websocket.server.WsFilter.doFilter (WsFilter.java:53) ~ [tomcat-embed-websocket-9.0.14.jar: 9.0.14] в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:193) ~ [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain.java:166) ~ [tomcat-embed-core-9.0.14.jar: 9.0.14] at org.springframework.web.filter.RequestContextFilter.doFilterInternal (RequestContextFilter.java:99) ~ [spring-web-5.1.4.RELEASE.jar: 5.1.4.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter (OncePerRequestFilter.java:107) ~ [spring-web-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:193) ~ [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain.java:166) ~ [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.springframework.web.filter.FormContentFilter.doFilterFternal.Content (Formjava: 92) ~ [spring-web-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в org.springframework.web.filter.OncePerRequestFilter.doFilter (OncePerRequestFilter.java:107) ~ [spring-web-5.1.4.RELEASE.jar: 5.1.4.RELEASE]в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:193) ~ [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain.java:166) ~ [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal (HiddenHttpMethodFilter.java:93) ~ [spring-web-5.1.4.RELEASE.jar: 5.1.4.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter (OncePerRequestFilter.java:107) ~ [spring-web-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:193) ~ [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain.java:166) ~ [tomcat-embed-core-9.0.14.jar: 9.0.14] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal (CharacterEncodingFilter.java:200) ~ [spring-web-5.1.4.RELEASE.jar: 5.1.4.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter (OncePerRequestFilter.java:107) ~ [spring-web-5.1.4.RELEASE.jar: 5.1.4.RELEASE] в org.apache.catalina.core.ApplicationFilterChain.internalDoFilter (ApplicationFilterChain.java:193) ~ [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain.java:166) ~ [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.catalina.core.StandardWrapperValve.invoke (StandardWrapperValve.java:199) ~ [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.catalina.core.StandardContextValve.invoke (StandardContextValve.java:96) [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.catalina.authenticator.AuthenticatorBase.invoke (AuthenticatorBase.java:490) [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.catalina.core.StandardHostValve.invoke (StandardHostValve.java:139) [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.catalina.valves.ErrorReportValve.invoke (ErrorReportValve.java:92) [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.catalina.core.StandardEngineValve.invoke (StandardEngineValve.java:74) [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.catalina.connector.CoyoteAdapter.service (CoyoteAdapter.java:343) [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.coyote.http11.Http11Processor.service (Http11Processor.java:408) [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.coyote.AbstractProcessorLight.process (AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.coyote.AbstractProtocol $ ConnectionHandler.process (AbstractProtocol.java:834) [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun (NioEndpoint.java:1417) [tomcat-embed-core-9.0.14.jar: 9.0.14] в org.apache.tomcat.util.net.SocketProcessorBase.run (SocketProcessorBase.java:49) [tomcat-embed-core-9.0.14.jar: 9.0.14] в java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1149) [na: 1.8.0_192-ea] в java.util.concurrent.ThreadPoolExecutor $ Worker.run (ThreadPoolExecutor.java:624) [na: 1.8.0_192-ea] в org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run (TaskThread.java:61) [tomcat-embed-core-9.0.14.jar: 9.0.14] at java.lang.Thread.run (Thread.java:748) [na: 1.8.0_192-ea]

...