java – Post mapping doesn’t work (message): “could not execute statement)

I am trying to create simple Rest project. When Post request is generated there is an error:

HTTP/1.1 500 
Content-Type: application/json
Transfer-Encoding: chunked
Date: Sun, 19 Jun 2022 14:33:09 GMT
Connection: close

{
  "timestamp": "2022-06-19T14:33:09.368+00:00",
  "status": 500,
  "error": "Internal Server Error",
  "trace": "org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statementrntat org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:276)rntat org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233)rntat org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:551)rntat org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)rntat org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)rntat org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152)rntat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)rntat org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174)rntat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)rntat org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)rntat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)rntat org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)rntat jdk.proxy4/jdk.proxy4.$Proxy103.save(Unknown Source)rntat com.example.service.StoreService.addStore(StoreService.java:19)rntat com.example.controller.StoreController.addStore(StoreController.java:20)rntat java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)rntat java.base/java.lang.reflect.Method.invoke(Method.java:577)rntat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)rntat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)rntat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)rntat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)rntat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)rntat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)rntat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)rntat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)rntat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)rntat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)rntat javax.servlet.http.HttpServlet.service(HttpServlet.java:681)rntat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)rntat javax.servlet.http.HttpServlet.service(HttpServlet.java:764)rntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)rntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)rntat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)rntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)rntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)rntat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)rntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)rntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)rntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)rntat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)rntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)rntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)rntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)rntat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)rntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)rntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)rntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)rntat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)rntat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)rntat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)rntat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)rntat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)rntat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)rntat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)rntat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)rntat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)rntat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890)rntat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1743)rntat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)rntat org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)rntat org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)rntat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)rntat java.base/java.lang.Thread.run(Thread.java:833)rnCaused by: org.hibernate.exception.ConstraintViolationException: could not execute statementrntat org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:109)rntat org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:37)rntat org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)rntat org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)rntat org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:200)rntat org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:58)rntat org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:43)rntat org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3279)rntat org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3885)rntat org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:84)rntat org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:645)rntat org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282)rntat org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263)rntat org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:317)rntat org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:330)rntat org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:287)rntat org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193)rntat org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:123)rntat org.hibernate.event.internal.DefaultMergeEventListener.saveTransientEntity(DefaultMergeEventListener.java:271)rntat org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:243)rntat org.hibernate.event.internal.DefaultMergeEventListener.entityIsDetached(DefaultMergeEventListener.java:318)rntat org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:172)rntat org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:70)rntat org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)rntat org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:829)rntat org.hibernate.internal.SessionImpl.merge(SessionImpl.java:816)rntat java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)rntat java.base/java.lang.reflect.Method.invoke(Method.java:577)rntat org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:362)rntat jdk.proxy4/jdk.proxy4.$Proxy99.merge(Unknown Source)rntat java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)rntat java.base/java.lang.reflect.Method.invoke(Method.java:577)rntat org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:311)rntat jdk.proxy4/jdk.proxy4.$Proxy99.merge(Unknown Source)rntat org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:650)rntat java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)rntat java.base/java.lang.reflect.Method.invoke(Method.java:577)rntat org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289)rntat org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137)rntat org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121)rntat org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:529)rntat org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:285)rntat org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:639)rntat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)rntat org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:163)rntat org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:138)rntat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)rntat org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80)rntat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)rntat org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)rntat org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)rntat org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)rntat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)rntat org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)rnt... 57 morernCaused by: org.postgresql.util.PSQLException: ОШИБКА: значение NULL в столбце "id" отношения "store" нарушает ограничение NOT NULLn  Подробности: Ошибочная строка содержит (null, null, Moscow).rntat org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2675)rntat org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2365)rntat org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:355)rntat org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:490)rntat org.postgresql.jdbc.PgStatement.execute(PgStatement.java:408)rntat org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:167)rntat org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:135)rntat com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)rntat com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)rntat org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197)rnt... 106 morern",
  "message": "could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
  "path": "/api/addStore"
}

Response code: 500; Time: 46ms; Content length: 14227 bytes

Store entity:

@Entity
@Table(name = "store")
public class Store {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    protected Integer id;

    @Column(name = "store_name")
    private String storeName;


    @Column(name = "address")
    private String address;

    public Store() {
    }

    public Store(Integer id, String storeName, String address) {
        this.id = id;
        this.storeName = storeName;
        this.address = address;
    }

    public Integer getId() {
        return id;
    }

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

    public String getStoreName() {
        return storeName;
    }

    public void setStoreName(String storeName) {
        this.storeName = storeName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Store store = (Store) o;
        return id.equals(store.id) && storeName.equals(store.storeName) && address.equals(store.address);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, storeName, address);
    }

    @Override
    public String toString() {
        return "Store{" +
                "id=" + id +
                ", storeName="" + storeName + "'' +
                ", address="" + address + "'' +
                '}';
    }
}

Store service:

@Service
public class StoreService implements IService {

    @Autowired
    private StoreRepository storeRepository;

    @Override
    public void addStore(Store store) {
        storeRepository.save(store);
    }

    @Override
    public List<Store> saveStores(List<Store> stores) {
        return storeRepository.saveAll(stores);
    }

    @Override
    public List<Store> getStores() {
        return storeRepository.findAll();
    }

    @Override
    public Store getStoreById(int id) {
        return storeRepository.findById(id).orElse(null);
    }

    @Override
    public Store getStoreByName(String name) {
        return storeRepository.findByStoreName(name);
    }

    public String deleteStore(int id) {
        storeRepository.deleteById(id);
        return "Store removed !! " + id;
    }

    @Override
    public Store updateStore(Store Store) {
        Store existingStore = storeRepository.findById(Store.getId()).orElse(null);
        existingStore.setStoreName(Store.getStoreName());
        existingStore.setAddress(Store.getAddress());
        return storeRepository.save(existingStore);
    }


}

Store controller:

@RestController
@RequestMapping("/api")
public class StoreController {

    @Autowired
    private StoreService storeService;

    @PostMapping("/addStore")
    public void addStore(@RequestBody Store store) {
        storeService.addStore(store);
    }

    @PostMapping("/addStores")
    public List<Store> addStores(@RequestBody List<Store> Stores) {
        return storeService.saveStores(Stores);
    }

    @GetMapping("/stores")
    public List<Store> findAllStores() {
        return storeService.getStores();
    }

    @GetMapping("/storeById/{id}")
    public Store findStoreById(@PathVariable int id) {
        return storeService.getStoreById(id);
    }

    @GetMapping("/store/{name}")
    public Store findStoreByName(@PathVariable String name) {
        return storeService.getStoreByName(name);
    }

    @PutMapping("/update")
    public Store updateStore(@RequestBody Store Store) {
        return storeService.updateStore(Store);
    }

    @DeleteMapping("/delete/{id}")
    public String deleteStore(@PathVariable int id) {
        return storeService.deleteStore(id);
    }
}

application.properties:

# ===============================
# DATABASE
# ===============================
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=1234
# ===============================
# JPA / HIBERNATE
# ===============================
spring.jpa.show-sql=true
spring.jpa.open-in-view = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.database=postgresql
#spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
#spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext
# ===============================
# LIQUIBASE
# ===============================
spring.liquibase.change-log =classpath:/db/changelog/db.changelog-master.xml
spring.liquibase.enabled = false

Other HTTP request (GET, UPDATE, DELETE) work correctly. When I try to use POSTfor example, there are an error:

POST http://localhost:8080/api/addStore
Content-Type: application/json

{
  "id" : 2,
  "store_name" : "Store 2",
  "address" : "Moscow"
}

Leave a Comment