No Session with spring.jpa.open-in-view=false - java

I have a Spring Boot 2.1 app with a simple rest controller, service tier, and data tier. I am attempting to disable spring.jpa.open-in-view as I want to manage the loading of my collections, etc. My problem seems to be when I disable open-in-view, I can't get anything back in my controller including simple properties including Strings.
Sample Project, simplified version of the code below:
https://github.com/csyperski/springbootopeninview
Here is my error:
2019-02-05 09:06:19.591 -ERROR 11355 --- [nio-8081-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : 175 : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.hibernate.LazyInitializationException: could not initialize proxy [com.cwssoft.pscafepos.model.Item#268] - no Session] with root cause
-
org.hibernate.LazyInitializationException: could not initialize proxy [com.cwssoft.pscafepos.model.Item#268] - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:169) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:309) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor.intercept(ByteBuddyInterceptor.java:45) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.proxy.ProxyConfiguration$InterceptorDispatcher.intercept(ProxyConfiguration.java:95) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at com.cwssoft.pscafepos.model.Item$HibernateProxy$h2GPuZuU.getBuilding(Unknown Source) ~[main/:na]
at com.cwssoft.pscafepos.controllers.ItemController.lambda$getSingle$3(ItemController.java:52) ~[main/:na]
at java.util.Optional.filter(Optional.java:178) ~[na:1.8.0_201]
at com.cwssoft.pscafepos.controllers.ItemController.getSingle(ItemController.java:52) ~[main/: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.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.3.RELEASE.jar:5.1.3.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.13.jar:9.0.13]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) ~[spring-security-web-5.1.2.RELEASE.jar:5.1.2.RELEASE]
Here is my Model without getters/setters:
import com.cwssoft.pscafepos.model.converters.BooleanToStringConverter;
import javax.persistence.*;
import java.util.Date;
#Entity
#Table(name="items", indexes = {
#Index(name="key_items_name", columnList="item_name"),
#Index(name="key_items_building", columnList="item_building"),
#Index(name="key_items_visible", columnList="item_visible"),
#Index(name="key_items_free", columnList="item_allowfree"),
#Index(name="key_items_reduced", columnList="item_allowreduced"),
#Index(name="key_items_typea", columnList="item_istypea"),
})
public class Item implements DomainObject {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "item_id", updatable = false, nullable = false)
private Long id;
#Column(name="item_name", length = 100, nullable = false, unique = false)
private String name;
#Column(name="item_description", columnDefinition = "TEXT")
private String description;
#Column(name="item_price")
private double price;
#Column(name="item_building", length = 100, nullable = false, unique = false)
private String building;
#Column(name="item_category", columnDefinition = "TEXT")
private String category;
#Column(name="item_visible", length = 1, nullable = false, unique = false)
#Convert(converter= BooleanToStringConverter.class)
private boolean visible;
#Column(name="item_allowfree", length = 1, nullable = false, unique = false)
#Convert(converter=BooleanToStringConverter.class)
private boolean allowFree;
#Column(name="item_allowreduced",length = 1, nullable = false, unique = false)
#Convert(converter=BooleanToStringConverter.class)
private boolean allowReduced;
#Column(name="item_istypea",length = 1, nullable = false, unique = false)
#Convert(converter=BooleanToStringConverter.class)
private boolean typeA;
#Column(name="item_reducedprice")
private double reducedPrice;
#Column(name="item_addby", length = 100, nullable = false, unique = false)
private String addedBy;
#Column(name="item_adddate")
#Temporal(TemporalType.TIMESTAMP)
private Date createDate;
#Column(name="item_fr_bl")
private int freeReducedBreakfastLunch;
}
Here is my Service Tier:
package com.cwssoft.pscafepos.services;
import com.cwssoft.pscafepos.model.Item;
import com.cwssoft.pscafepos.repositories.ItemRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
#Service
public class DefaultItemService extends BaseService<Item, ItemRepository> implements ItemService {
public DefaultItemService(ItemRepository itemRepository) {
super(itemRepository);
}
#Override
#Transactional
public Optional<Item> findByName(String name) {
if (name != null) {
return Optional.ofNullable(repository.findByName(name.trim()));
}
return Optional.empty();
}
#Override
#Transactional
public List<Item> findAll(String building) {
if (building != null) {
return repository.findByBuildingOrderByVisibleDescNameAsc(building.trim());
}
return Collections.emptyList();
}
}
and the service super class:
package com.cwssoft.pscafepos.services;
import com.cwssoft.pscafepos.model.DomainObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
#Slf4j
public abstract class BaseService<T extends DomainObject,U extends JpaRepository<T,Long>> implements CrudService<T,U> {
protected final U repository;
public BaseService(U repository) {
this.repository = repository;
}
public U getRepository() {
return repository;
}
#Transactional
public List<T> findAll() {
return repository.findAll();
}
#Transactional
public List<T> findAll(Sort sort) {
return repository.findAll(sort);
}
#Transactional
public List<T> findAllById(Iterable<Long> ids) {
return repository.findAllById(ids);
}
#Transactional
public Optional<T> save(T item) {
return Optional.ofNullable(repository.saveAndFlush(item));
}
#Transactional
public Optional<T> get(long id) {
return Optional.ofNullable(prepare(repository.getOne(id)));
}
#Transactional
public T prepare( T item ) {
return item;
}
#Transactional
public void delete(long id) {
get(id).ifPresent( repository::delete );
}
}
And the controller:
package com.cwssoft.pscafepos.controllers;
import com.cwssoft.pscafepos.model.AdminUser;
import com.cwssoft.pscafepos.model.Item;
import com.cwssoft.pscafepos.services.AdminUserService;
import com.cwssoft.pscafepos.services.ItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
#RestController
#RequestMapping("/items")
#Slf4j
public class ItemController extends BaseController {
private final ItemService service;
public ItemController(ItemService itemService, AdminUserService adminUserService) {
super(adminUserService);
this.service = itemService;
}
#GetMapping("/all")
#Secured("CAFE_MANAGER")
public List<Item> all(Principal principal) {
return getLocation(principal)
.map( service::findAll )
.orElse( Collections.emptyList() );
}
#GetMapping("/single/{itemId}")
#Secured("CAFE_MANAGER")
public Item getSingle(Principal principal, #PathVariable("itemId") long id) {
final Optional<String> location = getLocation(principal);
location
.flatMap( l -> service.get(id) )
.ifPresent( item -> {
log.info("Item.toString {}", item);
});
return location
.flatMap( l -> service.get(id) )
.filter( item -> item.getBuilding() != null && item.getBuilding().equalsIgnoreCase(location.orElse(null)) )
.orElse( null );
}
}
So what am I missing, why can't I pull back basic properties, there are no collections in the Item class and it about as simple as they come. I see that I'm getting a HibernateProxy wrapped object back and when I attempt to call getBuilding is when it appears to be failing, even though building is just a simple string. This is all before Jaskson is attempting to serialize the object to put it over the wire. Thanks!

Related

Unable to locate persister

I have the following problem when i try to do the findCliente method. I have the class Cliente in the package model and when i run the findCliente controller I get this exception here. I don't know where I'm wrong because I don't have much skill with JPA and Spring Suite. Can someone tell me how to fix this exception?
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Unable to locate persister: it.myshop.orm.model.Cliente
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java.lang.IllegalArgumentException: Unable to locate persister: it.myshop.orm.model.Cliente
org.hibernate.internal.SessionImpl.find(SessionImpl.java:3416)
org.hibernate.internal.SessionImpl.find(SessionImpl.java:3357)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:362)
com.sun.proxy.$Proxy41.find(Unknown Source)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:311)
com.sun.proxy.$Proxy41.find(Unknown Source)
it.myshop.orm.impl.ClienteServiceImpl.getById(ClienteServiceImpl.java:23)
it.myshop.orm.controller.ClienteController.findCliente(ClienteController.java:37)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
org.hibernate.UnknownEntityTypeException: Unable to locate persister: it.myshop.orm.model.Cliente
org.hibernate.metamodel.internal.MetamodelImpl.locateEntityPersister(MetamodelImpl.java:727)
org.hibernate.internal.SessionImpl.locateEntityPersister(SessionImpl.java:3019)
org.hibernate.internal.SessionImpl.access$1800(SessionImpl.java:201)
org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.<init>(SessionImpl.java:2715)
org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.<init>(SessionImpl.java:2698)
org.hibernate.internal.SessionImpl.byId(SessionImpl.java:1180)
org.hibernate.internal.SessionImpl.find(SessionImpl.java:3380)
org.hibernate.internal.SessionImpl.find(SessionImpl.java:3357)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:362)
com.sun.proxy.$Proxy41.find(Unknown Source)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:311)
com.sun.proxy.$Proxy41.find(Unknown Source)
it.myshop.orm.impl.ClienteServiceImpl.getById(ClienteServiceImpl.java:23)
it.myshop.orm.controller.ClienteController.findCliente(ClienteController.java:37)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
AppConfig
package it.myshop.orm.config;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
import it.myshop.orm.dao.ClienteService;
import it.myshop.orm.impl.ClienteServiceImpl;
#EnableWebMvc
#Configuration
#ComponentScan("it.myshop.orm.controller")
public class AppConfig {
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver iwv = new InternalResourceViewResolver();
iwv.setPrefix("/WEB-INF/view/");
iwv.setSuffix(".jsp");
iwv.setViewClass(JstlView.class);
return iwv;
}
//BEAN CONNESSIONE AL DB
#Bean
public DataSource getDbConnection() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/corso-spring-ud?serverTimezone=CET");
ds.setUsername("root");
return ds;
}
#Bean
public LocalContainerEntityManagerFactoryBean getEntityManager() {
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabase(Database.MYSQL);
adapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(getDbConnection());
factory.setJpaVendorAdapter(adapter); //passo adapter
factory.setPackagesToScan(getClass().getPackage().getName());
return factory;
}
#Bean
public ClienteService getClienteServiceImpl() {
return new ClienteServiceImpl();
}
App Initializer
package it.myshop.orm.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import it.myshop.orm.config.AppConfig;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return new Class<?>[] {AppConfig.class};
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[] {"/"};
}
}
ClienteController
package it.myshop.orm.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import it.myshop.orm.dao.ClienteService;
import it.myshop.orm.impl.ClienteServiceImpl;
import it.myshop.orm.model.Cliente;
#Controller
#RequestMapping("/cliente")
public class ClienteController {
#Autowired
private ClienteService cs;
#ResponseBody
#GetMapping("/add")
public String add() {
// cs.add(null);
System.out.println("Sei nella pagina di aggiunta");
return null;
}
#ResponseBody
#GetMapping("/findCliente")
public String findCliente() {
Cliente c = cs.getById(1);
System.out.println("Sei nella pagina di find del Cliente");
return c.getNome() + " " + c.getCognome();
}
Cliente
package it.myshop.orm.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="cliente")
public class Cliente {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column
private String nome;
#Column
private String cognome;
#Column
private String codiceFiscale;
#Column
private String email;
#Column
private String telefono;
#Column
private String username;
#Column
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public String getCodiceFiscale() {
return codiceFiscale;
}
public void setCodiceFiscale(String codiceFiscale) {
this.codiceFiscale = codiceFiscale;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Interface ClienteService
package it.myshop.orm.dao;
import it.myshop.orm.model.Cliente;
public interface ClienteService {
public Cliente add(Cliente c);
public Cliente getById(int id);
}
ClienteServiceImpl
package it.myshop.orm.impl;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import it.myshop.orm.dao.ClienteService;
import it.myshop.orm.model.Cliente;
public class ClienteServiceImpl implements ClienteService {
#PersistenceContext
public EntityManager em;
#Override
public Cliente add(Cliente c) {
em.persist(c);
return c;
}
#Override
public Cliente getById(int id) {
return em.find(Cliente.class, id);
}
}
In order to solve this problem you have two options. You can choose either of which .
1- you must have all you entity classes declared in you hibernate configuration file.
for this you must add you entity classes specially "Cliente" in hibernate.cfg.xml file
like this :
<mapping class="entity.Client"/>
or
2-another way is adding this entity to session configuration like this :
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml") .addAnnotatedClass(Cliente.class) .buildSessionFactory();

oracle.jdbc.OracleDatabaseException: ORA-01400: cannot insert NULL into ("SCOTT"."D_TEST"."DTESTID") in spring boot jpa

I am trying to add newtest through postmethod and getting this error.
unable to find the cause can someone help me
I don't know why it is taking null can someone help me
2021-05-12 06:14:47.963 ERROR 7048 --- [nio-8099-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-01400: cannot insert NULL into ("SCOTT"."D_TEST"."DTESTID")
2021-05-12 06:14:47.989 ERROR 7048 --- [nio-8099-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [/Test] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
oracle.jdbc.OracleDatabaseException: ORA-01400: cannot insert NULL into ("SCOTT"."D_TEST"."DTESTID")
at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:513) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:461) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1104) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:553) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:269) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:655) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:270) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:91) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:970) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1205) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3666) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at oracle.jdbc.driver.T4CPreparedStatement.executeInternal(T4CPreparedStatement.java:1426) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at oracle.jdbc.driver.OraclePreparedStatement.executeLargeUpdate(OraclePreparedStatement.java:3756) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3736) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1063) ~[ojdbc8-19.8.0.0.jar:19.8.0.0.0]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.5.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:45) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3195) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3801) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:84) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:645) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:317) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:330) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:287) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:123) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:185) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:128) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:55) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:93) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:720) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:706) ~[hibernate-core-5.4.30.Final.jar:5.4.30.Final]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) ~[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.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:362) ~[spring-orm-5.3.6.jar:5.3.6]
at com.sun.proxy.$Proxy85.persist(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:64) ~[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.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:311) ~[spring-orm-5.3.6.jar:5.3.6]
at com.sun.proxy.$Proxy85.persist(Unknown Source) ~[na:na]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:557) ~[spring-data-jpa-2.4.8.jar:2.4.8]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) ~[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.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289) ~[spring-data-commons-2.4.8.jar:2.4.8]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137) ~[spring-data-commons-2.4.8.jar:2.4.8]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121) ~[spring-data-commons-2.4.8.jar:2.4.8]
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:524) ~[spring-data-commons-2.4.8.jar:2.4.8]
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:285) ~[spring-data-commons-2.4.8.jar:2.4.8]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:531) ~[spring-data-commons-2.4.8.jar:2.4.8]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.6.jar:5.3.6]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:156) ~[spring-data-commons-2.4.8.jar:2.4.8]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:131) ~[spring-data-commons-2.4.8.jar:2.4.8]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.6.jar:5.3.6]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80) ~[spring-data-commons-2.4.8.jar:2.4.8]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.6.jar:5.3.6]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123) ~[spring-tx-5.3.6.jar:5.3.6]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388) ~[spring-tx-5.3.6.jar:5.3.6]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.6.jar:5.3.6]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.6.jar:5.3.6]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.6.jar:5.3.6]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.6.jar:5.3.6]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174) ~[spring-data-jpa-2.4.8.jar:2.4.8]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.6.jar:5.3.6]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.6.jar:5.3.6]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.6.jar:5.3.6]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.6.jar:5.3.6]
at com.sun.proxy.$Proxy89.save(Unknown Source) ~[na:na]
at com.cg.controller.IDiagnosticTestController.addNewTest(IDiagnosticTestController.java:45) ~[main/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) ~[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:197) ~[spring-web-5.3.6.jar:5.3.6]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141) ~[spring-web-5.3.6.jar:5.3.6]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.3.6.jar:5.3.6]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894) ~[spring-webmvc-5.3.6.jar:5.3.6]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.6.jar:5.3.6]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.6.jar:5.3.6]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060) ~[spring-webmvc-5.3.6.jar:5.3.6]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962) ~[spring-webmvc-5.3.6.jar:5.3.6]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.6.jar:5.3.6]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.6.jar:5.3.6]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:652) ~[tomcat-embed-core-9.0.45.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.6.jar:5.3.6]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.45.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.45.jar:9.0.45]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.45.jar:9.0.45]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.45.jar:9.0.45]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.45.jar:9.0.45]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.45.jar:9.0.45]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.6.jar:5.3.6]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.6.jar:5.3.6]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.45.jar:9.0.45]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.45.jar:9.0.45]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.6.jar:5.3.6]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.6.jar:5.3.6]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.45.jar:9.0.45]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.45.jar:9.0.45]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.6.jar:5.3.6]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.6.jar:5.3.6]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.45.jar:9.0.45]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.45.jar:9.0.45]
DiagnosticTest.java
package com.cg.entites;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import javax.persistence.CascadeType;
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.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
#Entity
#Table(name="d_test")
//#JsonNaming(PropertyNamingStrategy.LowerCaseStrategy.class)
public class DiagnosticTest implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="dtestid")
private int dtestid;
#Column(name="testname",nullable=true)
private String testname;
#Column(name="testprice",nullable=true)
private Integer testprice;
#Column(name="normalvalue",nullable=true)
private String normalvalue;
#Column(name="units")
private String units;
#ManyToMany(mappedBy="tests")
//#JsonIgnore
private Set<DiagnosticCenter> diagnosticCenters = new HashSet<>();
#JsonIgnore
public int getDtestid() {
return dtestid;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public void setDtestid(int dtestid) {
this.dtestid = dtestid;
}
public String getTestname() {
return testname;
}
public void setTestname(String testname) {
this.testname = testname;
}
public Integer getTestprice() {
return testprice;
}
public void setTestprice(Integer testprice) {
this.testprice = testprice;
}
public String getNormalvalue() {
return normalvalue;
}
public void setNormalvalue(String normalvalue) {
this.normalvalue = normalvalue;
}
public String getUnits() {
return units;
}
public void setUnits(String units) {
this.units = units;
}
public Set<DiagnosticCenter> getDiagnosticCenters() {
return diagnosticCenters;
}
public void setDiagnosticCenters(Set<DiagnosticCenter> diagnosticCenters) {
this.diagnosticCenters = diagnosticCenters;
}
#Override
public String toString() {
return "DiagnosticTest [dtestid=" + dtestid + ", testname=" + testname + ", testprice=" + testprice
+ ", normalvalue=" + normalvalue + ", units=" + units + ", diagnosticCenters=" + diagnosticCenters
+ "]";
}
}
DignosticCenter.java
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
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.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name="d_center")
public class DiagnosticCenter implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="dcenterid")
private int dcenterid;
#Column(name="name",nullable=true)
private String name;
#Column(name="contactNo",nullable=true)
private String contactNo;
#Column(name="address",nullable=true)
private String address;
#Column(name="contactEmail",nullable=true)
private String contactEmail;
#Column(name="servicesOffered",nullable=true)
private String servicesOffered;
#ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
#JoinTable(name = "center_test", joinColumns =
{ #JoinColumn(name = "dcenterId") },
inverseJoinColumns = { #JoinColumn(name = "dtestId")})
#JsonIgnore
private Set<DiagnosticTest> tests = new HashSet<>();
public int getDcenterid() {
return dcenterid;
}
public void setDcenterid(int dcenterid) {
this.dcenterid = dcenterid;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContactEmail() {
return contactEmail;
}
public void setContactEmail(String contactEmail) {
this.contactEmail = contactEmail;
}
public String getServicesOffered() {
return servicesOffered;
}
public void setServicesOffered(String servicesOffered) {
this.servicesOffered = servicesOffered;
}
public Set<DiagnosticTest> getTests() {
return tests;
}
public void setTests(Set<DiagnosticTest> tests) {
this.tests = tests;
}
#Override
public String toString() {
return "DiagnosticCenter [dcenterid=" + dcenterid + ", name=" + name + ", contactNo=" + contactNo + ", address="
+ address + ", contactEmail=" + contactEmail + ", servicesOffered=" + servicesOffered + "]";
}
}
DiagnosticTestRepository
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.cg.entites.DiagnosticCenter;
import com.cg.entites.DiagnosticTest;
import com.cg.exceptions.DiagnosticCenterNotFoundException;
#Repository
public interface IDiagnosticTestRepository extends JpaRepository<DiagnosticTest,Integer>{
/*public List<DiagnosticTest> getAllTest();
public DiagnosticTest addNewTest(DiagnosticTest test);
public List<DiagnosticTest> getTestsOfDiagnosticCenter(int dcenter_Id) throws DiagnosticCenterNotFoundException;
public DiagnosticTest updateTestDetail(DiagnosticTest test);
public DiagnosticTest removeTestFromDiagnosticCenter(int dcenter_Id, DiagnosticTest test) throws DiagnosticCenterNotFoundException;
*/
public DiagnosticTest findByDiagnosticCenters(int dcenterid) throws DiagnosticCenterNotFoundException;
public Optional<DiagnosticTest> findById(int dtestid);
}
DiagnosticCenterRepository
package com.cg.dao;
import java.util.List;
import java.util.Set;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.cg.entites.DiagnosticCenter;
import com.cg.entites.DiagnosticTest;
import com.cg.exceptions.DiagnosticCenterNotFoundException;
#Repository
public interface IDiagnosticCenterRepository extends JpaRepository<DiagnosticTest,Long>{
}
DiagnosticTestService
package com.cg.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.cg.entites.DiagnosticTest;
import com.cg.exceptions.DiagnosticCenterNotFoundException;
import com.cg.exceptions.TestNotFoundException;
#Service
public interface IDiagnosticTestService {
public List<DiagnosticTest> getAllTest();
public DiagnosticTest addNewTest(DiagnosticTest test);
public List<DiagnosticTest> getTestsOfDiagnosticCenter(int dcenterid) throws DiagnosticCenterNotFoundException;
public DiagnosticTest updateTestDetail(DiagnosticTest test);
public DiagnosticTest removeTestFromDiagnosticCenter(int dcenterid) throws DiagnosticCenterNotFoundException;
}
DiagnosticTestServiceImpl
package com.cg.service;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import javax.transaction.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.cg.dao.IDiagnosticCenterRepository;
import com.cg.dao.IDiagnosticTestRepository;
import com.cg.entites.DiagnosticCenter;
import com.cg.entites.DiagnosticTest;
import com.cg.exceptions.DiagnosticCenterNotFoundException;
import com.cg.exceptions.TestNotFoundException;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
#Service
public class IDiagnosticTestServiceImpl implements IDiagnosticTestService{
#Autowired
private IDiagnosticTestRepository dtestrepo;
#Autowired
private IDiagnosticCenterRepository dcenterrepo;
#Override
#Transactional
public List<DiagnosticTest> getAllTest() {
return dtestrepo.findAll();
}
#Override
#Transactional
public DiagnosticTest addNewTest(DiagnosticTest test){
DiagnosticTest dt=dtestrepo.save(test);
System.out.println(dt);
return dt;
}
#Override
public DiagnosticTest updateTestDetail(DiagnosticTest test) {
Optional<DiagnosticTest> dt=dtestrepo.findById(test.getDtestid());
if(dt.isPresent()) {
DiagnosticTest db=dt.get();
db.setTestname(test.getTestname());
db.setTestprice(test.getTestprice());
db.setNormalvalue(test.getNormalvalue());
db.setUnits(test.getUnits());
db.getDiagnosticCenters();
return dtestrepo.save(test);
}
return null;
}
#Override
public List<DiagnosticTest> getTestsOfDiagnosticCenter(int dcenterid) throws DiagnosticCenterNotFoundException {
// TODO Auto-generated method stub
return null;
}
#Override
public DiagnosticTest removeTestFromDiagnosticCenter(int dcenterid) throws DiagnosticCenterNotFoundException {
DiagnosticTest dt=dtestrepo.findByDiagnosticCenters(dcenterid);
System.out.println(dtestrepo.findByDiagnosticCenters(dcenterid));
dtestrepo.delete(dt);
return dt;
}
}
DiagnosticTestController
package com.cg.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
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.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.cg.dao.IDiagnosticTestRepository;
import com.cg.entites.DiagnosticTest;
import com.cg.exceptions.DiagnosticCenterNotFoundException;
import com.cg.exceptions.TestNotFoundException;
import com.cg.service.IDiagnosticTestService;
import com.cg.service.IDiagnosticTestServiceImpl;
#RestController
#RequestMapping("/api/v1")
public class IDiagnosticTestController {
#Autowired
IDiagnosticTestServiceImpl dtservice;
#Autowired
IDiagnosticTestRepository dtrepo;
#GetMapping("/dtest")
public List<DiagnosticTest> findAllTests(){
return dtrepo.findAll();
}
#PostMapping("/dtest/addtest")
public ResponseEntity<DiagnosticTest> addNewTest(
#RequestBody DiagnosticTest test){
return new ResponseEntity<DiagnosticTest>(dtrepo.save(test),HttpStatus.OK);
}
/* #GetMapping("/dtest/{dcenterId}")
public ResponseEntity<List<DiagnosticTest>> findTestsofDiagnosticCenter(
#PathVariable("dcenterId") int dcenterId) throws DiagnosticCenterNotFoundException{
List<DiagnosticTest> tests=dtservice.getTestsOfDiagnosticCenter(dcenterId);
if(tests!=null) {
return new ResponseEntity<List<DiagnosticTest>>(tests,HttpStatus.OK);
}
throw new DiagnosticCenterNotFoundException("diagnostic center is not found");
}*/
#PutMapping("/dtest/dtests")
public ResponseEntity<DiagnosticTest> updateTest(
#RequestBody DiagnosticTest test){
DiagnosticTest tests=dtservice.updateTestDetail(test);
if(tests==null) {
return new ResponseEntity("Sorry Tests are not available",HttpStatus.NOT_FOUND);
}
return new ResponseEntity<DiagnosticTest>(test,HttpStatus.OK);
}
#DeleteMapping("/removeTestFromDiagnosticCenter")
public ResponseEntity<DiagnosticTest> findByDiagnosticCenters(#RequestBody int dcenterid) throws DiagnosticCenterNotFoundException{
return new ResponseEntity<DiagnosticTest>(dtrepo.findByDiagnosticCenters(dcenterid), HttpStatus.OK);
// throw new DiagnosticCenterNotFoundException("centerId not found");
}
}
Please help me.
Since your indicates you're using ORACLE, I have to ask if you plan to use a database-side sequence (I would recommend it). Assuming you've created it, you should wire it in using something like #SequenceGenerator(name="my_entity_seq_gen", sequenceName="MY_ENTITY_SEQ").
It would go with the same ID field you have your #GeneratedValue annotation placed on.
Here is another SO question that discusses it and shows the syntax: Hibernate sequence on oracle, #GeneratedValue(strategy = GenerationType.AUTO)
With that your ORM should be able to defer to Oracle to generate a proper sequence for the ID to be saved upon initial persistence of the object (i.e. when you would be INSERTING it for the first time).
I think you can get away with NOT using an Oracle sequence, but I'm not 100% sure. (When I used oracle, I always did).
Another good thread on the topic: what is the use of annotations #Id and #GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?
Be sure to follow the "Oracle" tracks when reading these threads.
Since you have #GeneratedValue(strategy = GenerationType.IDENTITY) as the strategy the table in database must have identity generator. As explained in JPA docs below -
IDENTITY public static final GenerationType IDENTITY Indicates that
the persistence provider must assign primary keys for the entity using
a database identity column.
For example in Oracle 12c you can define identity column as
create table test (
test_col1 NUMBER GENERATED ALWAYS as IDENTITY(START with 1 INCREMENT by 1),
test_col2 VARCHAR2(10)
);

#SequenceGenerator throws After saving the identifier must not be null! when value of id not passed in h2

I am using spring boot with h2 database when using a sequence and using #SequenceGenerator doesn't seem to be generating the value for the primary key. I want to generate the value of Id by default and then update the values into the database.
Here are the details of my class.
CardHolder.java
package com.spring.book.rental.dao.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name = "card_holder")
public class CardHolder {
#Id
#Column
#GeneratedValue(generator="SEQ_CARD_HOLDER_ID",strategy=GenerationType.IDENTITY)
#SequenceGenerator(name="SEQ_CARD_HOLDER_ID",
sequenceName="SEQ_PG_CARD_HOLDER_ID",initialValue = 1)
public int id;
#Column(name = "last_name")
public String lastName;
#Column(name = "first_name")
public String firstName;
#Column(name = "card_number")
public String cardNumber;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
}
BookController.java
package com.spring.book.rental.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.spring.book.rental.DTO.BookDTO;
import com.spring.book.rental.DTO.RentBookRequest;
import com.spring.book.rental.service.BookService;
#RestController
public class BookController {
#Autowired
BookService bookService;
#PostMapping(path="book-rental/rentABook", consumes = "application/json")
public String rentABook(#RequestBody RentBookRequest bookRequest) {
try {
bookService.rentBook(bookRequest);
return "You rented a Book Id : "+bookRequest.getBookId();
} catch (Exception e) {
return e.getMessage();
}
}
}
BookServiceImpl.java
package com.spring.book.rental.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.spring.book.rental.DTO.BookDTO;
import com.spring.book.rental.DTO.RentBookRequest;
import com.spring.book.rental.dao.BookDAO;
import com.spring.book.rental.dao.CardHolderDAO;
import com.spring.book.rental.dao.RentalDAO;
import com.spring.book.rental.dao.model.Book;
import com.spring.book.rental.dao.model.CardHolder;
import com.spring.book.rental.dao.model.Rental;
import com.spring.book.rental.service.BookService;
#Service("bookService")
#Component
public class BookServiceImpl implements BookService {
#Autowired
BookDAO bookDao;
#Autowired
CardHolderDAO cardHolderDAO;
#Autowired
RentalDAO rentalDAO;
#Override
public void rentBook(RentBookRequest bookRequest) throws Exception {
CardHolder cardHolder = new CardHolder();
cardHolder.setFirstName(bookRequest.getFirstName());
cardHolder.setLastName(bookRequest.getLastName());
cardHolder.setCardNumber(bookRequest.getCardNumber());
cardHolderDAO.addCardHolder(cardHolder);
/* Rental rental = new Rental();
rental.setBook_id(bookRequest.getBookId());
rental.setCardHolder_id(cardHolder.getId());
rentalDAO.addRental(rental); */
}
}
CardHolderDAOImpl.java
package com.spring.book.rental.dao.impl;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.spring.book.rental.dao.CardHolderDAO;
import com.spring.book.rental.dao.model.CardHolder;
import com.spring.book.rental.dao.repository.CardHolderRepository;
#Repository
public class CardHolderDAOImpl implements CardHolderDAO {
#Autowired
CardHolderRepository cardHolderRepository;
#Override
public void addCardHolder(CardHolder cardHolder) {
cardHolderRepository.save(cardHolder);
}
}
CardHolderRepository.java
package com.spring.book.rental.dao.repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import com.spring.book.rental.dao.model.CardHolder;
public interface CardHolderRepository extends CrudRepository<CardHolder, Integer> {
public Optional<CardHolder> findById(Integer id);
}
RentBookRequest.java
package com.spring.book.rental.DTO;
public class RentBookRequest {
private int bookId;
private int cardHolderId;
private String firstName;
private String lastName;
private String cardNumber;
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public int getCardHolderId() {
return cardHolderId;
}
public void setCardHolderId(int cardHolderId) {
this.cardHolderId = cardHolderId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
}
Here is the main class
SpringTaskBookRentalApplication.java
package com.spring.book.rental;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import sun.misc.Contended;
#ComponentScan(basePackages = "com")
#EnableAutoConfiguration
#SpringBootApplication
public class SpringTaskBookRentalApplication {
public static void main(String[] args) {
SpringApplication.run(SpringTaskBookRentalApplication.class, args);
}
}
I have added this in the application.properties file
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:bookrentaldb
spring.datasource.username=admin
spring.datasource.password=admin
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.datasource.continue-on-error=false
spring.datasource.initialize=true
spring.datasource.separator=;
spring.datasource.sql-script-encoding=UTF-8
Here is the schema.sql file
create table BOOK(
id int not null primary key,
title varchar(50) not null,
IS_BOOK_AVAILABLE boolean not null,
author varchar(50) not null,
primary key(id)
);
create table card_holder (
id int not null primary key AUTO_INCREMENT,
first_name varchar(20),
last_name varchar(20),
card_number varchar(20),
primary key(id)
);
create table Rental(
rental_id int not null primary key AUTO_INCREMENT,
cardHolder_id int not null,
book_id int not null
);
CREATE SEQUENCE SEQ_PG_CARD_HOLDER_ID MINVALUE 1 MAXVALUE 9999 INCREMENT BY 1 START WITH 1 NOCYCLE ;
CREATE SEQUENCE SEQ_PG_Rental_ID MINVALUE 1 MAXVALUE 999999 INCREMENT BY 1 START WITH 100 NOCYCLE ;
Here is the data.sql
insert into BOOK (id,title,IS_BOOK_AVAILABLE,author) values (101,'A Thousand Splendid Suns','true','Khalid Hosseini');
insert into BOOK (id,title,IS_BOOK_AVAILABLE,author) values (102,'Head First Design Patterns','true','Elisabeth Freeman and Kathy Sierra');
insert into BOOK (id,title,IS_BOOK_AVAILABLE,author) values (103,'Head First Java','true','Book by Bert Bates and Kathy Sierra');
commit;
I have tried several other things with #GeneratedValue
#Id
#Column
#GeneratedValue(strategy=GenerationType.AUTO)
public int id;
This is the stackTrace of error I am getting
java.lang.IllegalArgumentException: After saving the identifier must not be null!
at org.springframework.util.Assert.notNull(Assert.java:198)
at org.springframework.data.jdbc.core.JdbcAggregateTemplate.store(JdbcAggregateTemplate.java:343)
at org.springframework.data.jdbc.core.JdbcAggregateTemplate.save(JdbcAggregateTemplate.java:149)
at org.springframework.data.jdbc.repository.support.SimpleJdbcRepository.save(SimpleJdbcRepository.java:55)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.data.repository.core.support.ImplementationInvocationMetadata.invoke(ImplementationInvocationMetadata.java:72)
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:382)
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:205)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:549)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:155)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:130)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy81.save(Unknown Source)
at com.spring.book.rental.dao.impl.CardHolderDAOImpl.addCardHolder(CardHolderDAOImpl.java:38)
at com.spring.book.rental.dao.impl.CardHolderDAOImpl$$FastClassBySpringCGLIB$$8e01a85d.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
at com.spring.book.rental.dao.impl.CardHolderDAOImpl$$EnhancerBySpringCGLIB$$5a6f1054.addCardHolder(<generated>)
at com.spring.book.rental.service.impl.BookServiceImpl.rentBook(BookServiceImpl.java:68)
at com.spring.book.rental.controller.BookController.rentABook(BookController.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
You are adding lot of dependencies which you don't need. And when you add a dependency that you don't need, spring boot tries to guess the type of your application and configures accordingly.
I also recommend reading Spring data JPA vs Spring Data JDBC as both are mixed.
1.
public CardHolder addCardHolder(CardHolder cardHolder) {
return cardHolderRepository.save(cardHolder);
}
#Override
public void rentBook(RentBookRequest bookRequest) throws Exception {
CardHolder cardHolder = new CardHolder();
cardHolder.setFirstName(bookRequest.getFirstName());
cardHolder.setLastName(bookRequest.getLastName());
cardHolder.setCardNumber(bookRequest.getCardNumber());
CardHolder saved = cardHolderDAO.addCardHolder(cardHolder);
Rental rental = new Rental();
rental.setBook_id(bookRequest.getBookId());
rental.setCardHolder_id(saved.getId());
rentalDAO.addRental(rental);
}
Your pom should contain only the following. You are currently adding many different dependencies
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
package com.spring.book.rental.dao.model;
import javax.persistence.*;
#Entity
#Table(name = "BOOK")
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public int id;
#Column
public String title;
#Column(name = "IS_BOOK_AVAILABLE")
public boolean isBookAvailable;
#Column
public String author;
...
package com.spring.book.rental.dao.model;
import javax.persistence.*;
#Entity
#Table(name = "card_holder")
public class CardHolder {
#Id
#GeneratedValue(generator="SEQ_CARD_HOLDER_ID",strategy=GenerationType.IDENTITY)
#SequenceGenerator(name="SEQ_CARD_HOLDER_ID", sequenceName="SEQ_PG_CARD_HOLDER_ID",initialValue = 1)
#Column
public int id;
#Column(name = "last_name")
public String lastName;
#Column(name = "first_name")
public String firstName;
#Column(name = "card_number")
public String cardNumber;
....
package com.spring.book.rental.dao.model;
import javax.persistence.*;
import org.springframework.boot.autoconfigure.domain.EntityScan;
#Entity
#Table(name = "Rental")
public class Rental {
#Id
#Column(name = "rental_id")
#GeneratedValue(strategy = GenerationType.AUTO)
public int rentalId;
#Column(name = "cardHolder_id")
public int cardHolder_id;
#Column(name = "book_id")
public int book_id;
....
package com.spring.book.rental.dao.repository;
import com.spring.book.rental.dao.model.Book;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
import java.util.Optional;
public interface BookRepository extends CrudRepository<Book,Integer>{
public List<Book> findAllByIsBookAvailableTrue();
public List<Book> findAll();
public Optional<Book> findById(Integer id);
}
...
Delete schema.sql as it has mistakes and JPA can auto create it.
application properties
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

org.springframework.web.util.NestedServletException and org.hibernate.HibernateException: No Session found for current thread

i am trying to insert some record into my database table using spring hibernate,but the following error occur after running the project.please help me to solve the problem..thanks
Entity class Admin.java
package com.finalproject.entity;
// Generated Apr 20, 2017 4:49:19 PM by Hibernate Tools 4.3.1
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Admin generated by hbm2java
*/
#Entity
#Table(name="admin"
,catalog="advertisement_system"
)
public class Admin implements java.io.Serializable {
private Integer adminId;
private String adminName;
private String adminEmail;
private String adminPass;
private byte[] adminPhoto;
public Admin() {
}
public Admin(String adminName, String adminEmail, String adminPass) {
this.adminName = adminName;
this.adminEmail = adminEmail;
this.adminPass = adminPass;
}
public Admin(String adminName, String adminEmail, String adminPass, byte[] adminPhoto) {
this.adminName = adminName;
this.adminEmail = adminEmail;
this.adminPass = adminPass;
this.adminPhoto = adminPhoto;
}
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="admin_id", unique=true, nullable=false)
public Integer getAdminId() {
return this.adminId;
}
public void setAdminId(Integer adminId) {
this.adminId = adminId;
}
#Column(name="admin_name", nullable=false, length=45)
public String getAdminName() {
return this.adminName;
}
public void setAdminName(String adminName) {
this.adminName = adminName;
}
#Column(name="admin_email", nullable=false, length=45)
public String getAdminEmail() {
return this.adminEmail;
}
public void setAdminEmail(String adminEmail) {
this.adminEmail = adminEmail;
}
#Column(name="admin_pass", nullable=false, length=45)
public String getAdminPass() {
return this.adminPass;
}
public void setAdminPass(String adminPass) {
this.adminPass = adminPass;
}
#Column(name="admin_photo")
public byte[] getAdminPhoto() {
return this.adminPhoto;
}
public void setAdminPhoto(byte[] adminPhoto) {
this.adminPhoto = adminPhoto;
}
}
AdminServiceImpl.java class
package com.finalproject.service.impl;
import com.finalproject.dao.AdminDao;
import com.finalproject.entity.Admin;
import com.finalproject.service.AdminService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
#Service("adminService")
#Transactional(propagation = Propagation.SUPPORTS,rollbackFor = Exception.class)
public class AdminServiceImpl implements AdminService {
#Autowired
AdminDao adminDao;
#Override
public void create(Admin admin) {
adminDao.create(admin);
}
#Override
public void update(Admin admin) {
adminDao.update(admin);
}
#Override
public void delete(Long adminId) {
adminDao.delete(adminId);
}
#Override
public Admin edit(Long adminId) {
return adminDao.edit(adminId);
}
#Override
public List<Admin> getAll() {
return adminDao.getAll();
}
#Override
public Admin find(Long adminId) {
return adminDao.find(adminId);
}
}
Dao implemented class AdminDaoImpl.java
package com.finalproject.dao.impl;
import com.finalproject.dao.AdminDao;
import com.finalproject.entity.Admin;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository("adminDao")
public class AdminDaoImpl implements AdminDao {
#Autowired
SessionFactory sessionFactory;
protected Session currentSession() {
return sessionFactory.getCurrentSession();
}
#Override
public void create(Admin admin) {
currentSession().save(admin);
}
#Override
public void update(Admin admin) {
currentSession().update(admin);
}
#Override
public void delete(Long adminId) {
currentSession().delete(adminId);
}
#Override
public Admin edit(Long adminId) {
return find(adminId);
}
#Override
public Admin find(Long adminId) {
return (Admin) currentSession().get(Admin.class, adminId);
}
#Override
public List<Admin> getAll() {
return currentSession().createCriteria(Admin.class).list();
}
}
controller class AdminController.java
package com.finalproject.controller;
import com.finalproject.entity.Admin;
import com.finalproject.service.AdminService;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping(value = "/admin")
public class AdminController {
#Autowired
AdminService adminService;
#RequestMapping(value = "/register", method = RequestMethod.GET)
public String register(Map<String, Object> map) {
map.put("adminReg", new Admin());
return "/admin/add";
}
#RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(Admin admin, Map<String, Object> map) {
adminService.create(admin);
return "redirect:/admin/details/" + admin.getAdminId();
}
#RequestMapping(value = "/details/{adminId}",method = RequestMethod.GET)
public String details(#PathVariable("adminId") Long adminId, Map<String, Object> map) {
Admin admin = adminService.find(adminId);
map.put("adminName", admin.getAdminName());
map.put("adminEmail", admin.getAdminEmail());
map.put("adminPass", admin.getAdminPass());
return "admin/details";
}
}
Error message
type Exception report
message Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:948)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
root cause
org.hibernate.HibernateException: No Session found for current thread
org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:978)
com.finalproject.dao.impl.AdminDaoImpl.currentSession(AdminDaoImpl.java:19)
com.finalproject.dao.impl.AdminDaoImpl.create(AdminDaoImpl.java:24)
com.finalproject.service.impl.AdminServiceImpl.create(AdminServiceImpl.java:22)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
com.sun.proxy.$Proxy125.create(Unknown Source)
com.finalproject.controller.AdminController.create(AdminController.java:29)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
Error Message
AdminDaoImpl.java

How to delete record using primarykey in dynamodb

I get the record using primarykey id in amazon dynamodb using java.
AccountController.java
package com.dynamodb.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.account.json.AccountJson;
import com.account.service.AccountService;
#Controller
public class AccountController extends AbstractServiceController {
#Autowired
private AccountService accountService;
#RequestMapping(value = "/deleteAccountByAccountId", method = RequestMethod.POST)
public #ResponseBody String deleteAccountByAccountId(#RequestBody AccountJson accountJson) {
try {
Boolean bool = accountService.deleteAccountByAccountId(accountJson.getAccountId());
if (bool) {
return "Record deleted Successfully";
} else {
return "Record not deleted";
}
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
AccountService.java
package com.account.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.account.dao.AccountRepository;
#Service
public class AccountService {
#Autowired
private AccountRepository accountRepository;
public Boolean deleteAccountByAccountId(String accountId) {
return accountRepository.deleteAccountByAccountId(accountId);
}
}
AccountRepository.java
package com.account.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ComparisonOperator;
import com.amazonaws.services.dynamodbv2.model.Condition;
import com.account.datastore.Account;
#Repository
public class AccountRepository extends BaseRepository {
public Account getAccountByAccountId(String accountId) {
Account account = null;
try {
DynamoDBMapper mapper = getDynameDbMapper();
DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
scanExpression.addFilterCondition("accountId", new Condition().withComparisonOperator(ComparisonOperator.EQ).withAttributeValueList(new AttributeValue().withS(accountId)));
List<Account> accounts = mapper.scan(Account.class, scanExpression);
if (accounts != null && accounts.size() > 0) {
account = accounts.get(0);
}
} catch (Exception e) {
e.printStackTrace();
}
return account;
}
public Boolean deleteAccountByAccountId(String accountId) {
try {
Account account = getAccountByAccountId(accountId);
if (account != null) {
DynamoDBMapper mapper = getDynameDbMapper();
mapper.delete(account);
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
Account.java
package com.account.datastore;
import java.io.Serializable;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
#DynamoDBTable(tableName = "cd_accounts")
public class Account implements Serializable {
private static final long serialVersionUID = 244669855912873613L;
#DynamoDBAutoGeneratedKey
#DynamoDBHashKey
private String accountId;
private String documentTypeId;
private String accountName;
private Long isActive;
private Long isBill;
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getDocumentTypeId() {
return documentTypeId;
}
public void setDocumentTypeId(String documentTypeId) {
this.documentTypeId = documentTypeId;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public Long getIsActive() {
return isActive;
}
public void setIsActive(Long isActive) {
this.isActive = isActive;
}
public Long getIsBill() {
return isBill;
}
public void setIsBill(Long isBill) {
this.isBill = isBill;
}
}
Error is occurred while deleting the record. How to delete the record in amazon dynamodb using java.
com.amazonaws.AmazonServiceException: The provided key element does not match the schema (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: NR1SVIM98PVPFNHUOL49EI4JPFVV4KQNSO5AEMVJF66Q9ASUAAJG)
10:02:18,739 ERROR [AccountRepository] deleteAccountByAccountId Error:The provided key element does not match the schema (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: NR1SVIM98PVPFNHUOL49EI4JPFVV4KQNSO5AEMVJF66Q9ASUAAJG)
10:02:18,739 DEBUG [AccountController] --------------deleteAccountByAccountId----------------END------------------
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1077)
at com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:725)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:460)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:295)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:3106)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.deleteItem(AmazonDynamoDBClient.java:967)
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.delete(DynamoDBMapper.java:1364)
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.delete(DynamoDBMapper.java:1272)
at com.account.dao.AccountRepository.deleteAccountByAccountId(AccountRepository.java:110)
at com.account.service.AccountService.deleteAccountByAccountId(AccountService.java:40)
at com.account.controller.AccountController.deleteAccountByAccountId(AccountController.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
documentTypeId is primarykey for cd_documentTypes table, this primarykey is used in cd_accounts table as a foreignkey.
If the table having foreignkey relation we must mention the #DynamoDBRangeKey annotation above documentTypeId attribute in Account class. Problem is solved after declared the #DynamoDBRangeKey on top of the attribute documentTypeId.
#DynamoDBRangeKey
private String documentTypeId;
If we want to save or update or delete records in amazon dynamodb using java we must mention the
annotation #DynamoDBHashKey on top of the primarykey column.
#DynamoDBAutoGeneratedKey
#DynamoDBHashKey
private String accountId;
Below is the image shown for foreignkey relation exists in cd_accounts table.
Note:Range key attribute field is displayed if the table is mapping to another table primarykey in amaozong dynamodb.

Categories