I've been building an app and im finally getting the front end and back to communicate.in my springboot controller im getting a new error. One that from my research occurs from having to many to one relation a solution is json ignore.but the problem with that is the json info is obviously ignored.how can i save from my controller more then one instance of a user. Without getting this error
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.ArrayList[0]->com.example.realtyKing.Account.GeneralUser.Model.User["gender"]->com.example.realtyKing.Account.GeneralUser.Model.Gender$HibernateProxy$0WkqjT1u["hibernateLazyInitializer"])
at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:77) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.SerializerProvider.reportBadDefinition(SerializerProvider.java:1300) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.DatabindContext.reportBadDefinition(DatabindContext.java:400) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:46) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:29) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:774) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase._serializeWithObjectId(BeanSerializerBase.java:684) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:171) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:774) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase._serializeWithObjectId(BeanSerializerBase.java:684) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:171) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:119) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serialize(IndexedListSerializer.java:79) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serialize(IndexedListSerializer.java:18) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:400) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1514) ~[jackson-databind-2.13.3.jar:2.13.3]
at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:1007) ~[jackson-databind-2.13.3.jar:2.13.3]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:456) ~[spring-web-5.3.20.jar:5.3.20]
at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:104) ~[spring-web-5.3.20.jar:5.3.20]
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:290) ~[spring-webmvc-5.3.20.jar:5.3.20]
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:183) ~[spring-webmvc-5.3.20.jar:5.3.20]
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:78) ~[spring-web-5.3.20.jar:5.3.20]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:135) ~[spring-webmvc-5.3.20.jar:5.3.20]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.3.20.jar:5.3.20]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.20.jar:5.3.20]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.20.jar:5.3.20]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067) ~[spring-webmvc-5.3.20.jar:5.3.20]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.20.jar:5.3.20]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.20.jar:5.3.20]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.3.20.jar:5.3.20]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:655) ~[tomcat-embed-core-9.0.63.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.20.jar:5.3.20]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.63.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.63.jar:9.0.63]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.20.jar:5.3.20]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.20.jar:5.3.20]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.20.jar:5.3.20]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.20.jar:5.3.20]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:142) ~[spring-session-core-2.7.0.jar:2.7.0]
at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:82) ~[spring-session-core-2.7.0.jar:2.7.0]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.20.jar:5.3.20]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.20.jar:5.3.20]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1743) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.63.jar:9.0.63]
at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]
my user class
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
#Getter
#Setter
#Builder
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "user", uniqueConstraints = #UniqueConstraint(columnNames = "email"))
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "first_name", nullable = false)
private String firstName;
#Column(name = "middle_name")
private String middleName;
#Column(name = "last_name", nullable = false)
private String lastName;
#Column(nullable = false)
private Date dob;
#Column(name = "phone_number", nullable = false)
private String phoneNumber;
#Column(nullable = false)
private String email;
#Column(nullable = false)
private String password;
#Column(nullable = false)
private Boolean isActive;
#Column(name = "email_config")
private String emailConfig;
#OneToOne(mappedBy = "user")
private Employee employee;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(
name = "user_role",
joinColumns = #JoinColumn(
name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(
name = "role_id", referencedColumnName = "id"))
private Collection < Role > roles;
#OneToMany(fetch=FetchType.LAZY, mappedBy="user")
private Set<AttachmentValue> attachmentValues;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "gender_id", nullable = false)
private Gender gender;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "account_privilege_id")
private AccountPrivilege accountPrivilege;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(
name = "user_offer",
joinColumns = #JoinColumn(
name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(
name = "property_offer_id", referencedColumnName = "id"))
private Collection < PropertyOffer> propertyOffers;
#OneToMany(fetch=FetchType.LAZY, mappedBy="user")
private Set<Building> buildings;
#OneToMany(fetch=FetchType.LAZY, mappedBy="user")
private Set<Payroll> payrolls;
public User(String firstName, String lastName, Date dob, String phoneNumber, String email,
String password, Collection < Role > roles, Gender gender, AccountPrivilege accountPrivilege)
{
super();
this.firstName = firstName;
this.lastName = lastName;
this.dob = dob;
this.phoneNumber=phoneNumber;
this.email = email;
this.password = password;
this.roles = roles;
this.gender=gender;
this.accountPrivilege= accountPrivilege;
}
}
the two classes it has a many to many relationships with.
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
#Getter
#Setter
#Builder
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "gender")
public class Gender {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(nullable = false)
private String gender;
#OneToMany(fetch=FetchType.LAZY, mappedBy="gender")
private Set<User> users;
}
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
#Getter
#Setter
#Builder
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "account_privilege")
public class AccountPrivilege {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "enable_slideshow", nullable = false)
private Boolean enableSlideshow;
#Column(name = "privilege_name", nullable = false)
private String privilegeName;
#Column(nullable = false)
private float priority;
#Column(name = "privilege_price", nullable = false)
private float privilegePrice;
#OneToMany(fetch=FetchType.LAZY, mappedBy="accountPrivilege")
private Set<User> users;
}
Use Jackson's managed references.
https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion
Also, best practice is to map your JPA entities to a separate set of pojos for your controllers. Mapping frameworks like MapStruct exist for this reason to eliminate all the boilerplate. Going that route avoids this problem all together and will make your pojos less cluttered from all the annotations.
Related
I am trying to pull features of a product using hibernate API in Spring Boot application.
Feature.java
#Entity
#Table(name = "feature")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Feature extends BaseEntity {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(generator = "UUID")
#GenericGenerator(
name = "UUID",
strategy = "org.hibernate.id.UUIDGenerator"
)
#Column(name = "id", updatable = false)
private String id;
#Column(name = "name")
private String name;
#Column(name = "code", updatable = false)
private String code;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "product_id", referencedColumnName = "id")
private Product product;
// getters & setters
}
#Entity
#Table(name = "product")
public class Product extends BaseEntity {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(generator = "UUID")
#GenericGenerator(
name = "UUID",
strategy = "org.hibernate.id.UUIDGenerator"
)
#Column(name = "id", updatable = false)
private String id;
#Column(name = "name")
private String name;
#Column(name = "code", updatable = false)
private String code;
// getters & setters
}
when i call below method in Rest Controller class
#GetMapping("/list/{productId}")
public ResponseEntity<List<Feature>> retrieveList(#PathVariable("productId") String productId) {
List<Feature> featureList = featureService.retrieveListByProductId(productId);
return new ResponseEntity<>(featureList, HttpStatus.OK);
}
#Override
#Transactional
public List<Feature> retrieveListByProductId(String productId) {
return featureRepo.retrieveListByProductId(productId);
}
#Override
public List<Feature> retrieveListByProductId(String productId) {
Session session = sessionFactory.getCurrentSession();
String queryString = "from Feature f where f.product.id = :productId order by f.name";
Query<Feature> query = session.createQuery(queryString, Feature.class);
query.setParameter("productId", productId);
return query.getResultList();
}
i am getting
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.ArrayList[0]->com.cm.entity.Feature["product"]->com.cm.entity.Product$HibernateProxy$HyMnl1iV["hibernateLazyInitializer"])
at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:77)
at com.fasterxml.jackson.databind.SerializerProvider.reportBadDefinition(SerializerProvider.java:1300)
at com.fasterxml.jackson.databind.DatabindContext.reportBadDefinition(DatabindContext.java:400)
at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:46)
at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:29)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:774)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:774)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178)
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:145)
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:107)
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:25)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:400)
at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1514)
at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:1007)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:456)
at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:104)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:290)
at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:219)
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:78)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:135)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1071)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:964)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:670)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:779)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:833)
I added below property in Spring Boot(2.7.5)
spring.jackson.serialization.fail-on-empty-beans=false
in application.properties file. But still, it is throwing an exception.
I also tried by changing from FetchType.LAZY to FetchType.EAGER. Though it is working, i want to load product lazyly.
I tried the post. Still getting the same error
Can someone help me to fix it
#Entity
#Table(name="blogs")
public class Blog {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(nullable = false, length = 300)
private String title;
#Lob #Column (nullable = false)
private String body;
#Column(nullable=false)
private Date date =new Date();
#ManyToOne(optional = false,fetch = FetchType.LAZY)
#JoinColumn(name="user_id",referencedColumnName = "id", nullable= false)
private User user;
public Blog() {}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
this is my Blog class
import java.awt.print.PageFormat;
import java.awt.print.Pageable;
import java.awt.print.Printable;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Service;
#Service
#Primary
public class BlogServiceImpl implements BlogService{
#Autowired
private BlogRepository blogrepo;
#Override
public List<Blog> findAll() {
// TODO Auto-generated method stub
return this.blogrepo.findAll();
}
#Override
public List<Blog> findLatest5() {
return this.blogrepo.findLatest5Blogs(new QPageRequest(0, 5));
}
#Override
public Blog findById(Long id) {
// TODO Auto-generated method stub
return blogrepo.findById(id).get();
}
#Override
public Blog create(Blog blog) {
// TODO Auto-generated method stub
return this.blogrepo.save(blog);
}
#Override
public Blog edit(Blog blog) {
// TODO Auto-generated method stub
return this.blogrepo.save(blog);
}
#Override
public void deleteById(Long id) {
this.blogrepo.deleteById(id);;
}
}
my blogServiceImplementation
import java.awt.print.Pageable;
import java.util.List;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Repository;
import com.example.demo.Blog;
#Repository
public interface BlogRepository extends JpaRepository<Blog, Long>{
#Query("SELECT b FROM Blog b LEFT JOIN FETCH b.user ORDER BY b.date DESC")
List<Blog> findLatest5Blogs(QPageRequest qPageRequest);
}
my blog Repository
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(nullable = false, unique = true, length = 45)
private String email;
#Column(nullable = false, unique = true, length = 45)
private String username;
#Column(nullable = false, length = 64)
private String password;
#Column(name = "first_name", nullable = false, length = 20)
private String firstName;
#Column(name = "last_name", nullable = false, length = 20)
private String lastName;
#Column(name = "user_role")
private String user_role;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="account_id")
private accountInfo accountinfo;
public User() {}
#OneToMany(mappedBy="user")
private List<Blog> blogs= new ArrayList<Blog>();
// #PrePersist
// public void prepareToInsert() {
// List<User> conflicts = find("username=?").fetch();
// if (!conflicts.isEmpty()) {
// throw new IllegalArgumentException("username `" + username + "` is already taken");
// }
// }
//
public String getUser_role() {
return user_role;
}
public void setUser_role(String user_role) {
this.user_role = user_role;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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 getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public accountInfo getAccountinfo() {
return accountinfo;
}
public void setAccountinfo(accountInfo accountinfo) {
this.accountinfo = accountinfo;
}
public List<Blog> getBlogs() {
return blogs;
}
public void setBlogs(List<Blog> blogs) {
this.blogs = blogs;
}
}
and my User class
when I try to get all the Blogs its working but when i try to use the method for printing only 5 on them on 1 page Im getting this error
java.lang.ClassNotFoundException: com.querydsl.core.types.OrderSpecifier
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602) ~[na:na]
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) ~[na:na]
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522) ~[na:na]
at org.springframework.data.querydsl.QSort.<clinit>(QSort.java:41) ~[spring-data-commons-2.5.2.jar:2.5.2]
at org.springframework.data.querydsl.QPageRequest.<init>(QPageRequest.java:49) ~[spring-data-commons-2.5.2.jar:2.5.2]
at com.example.demo.BlogServiceImpl.findLatest5(BlogServiceImpl.java:29) ~[classes/:na]
at com.example.demo.AppController.viewKnowledge(AppController.java:86) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[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.8.jar:5.3.8]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1063) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.3.8.jar:5.3.8]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:655) ~[tomcat-embed-core-9.0.48.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.8.jar:5.3.8]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.48.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:228) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.springframework.web.servlet.resource.ResourceUrlEncodingFilter.doFilter(ResourceUrlEncodingFilter.java:67) ~[spring-webmvc-5.3.8.jar:5.3.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:121) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:105) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter.doFilterInternal(DefaultLogoutPageGeneratingFilter.java:58) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:237) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:223) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:218) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:117) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183) ~[spring-security-web-5.5.1.jar:5.5.1]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) ~[spring-web-5.3.8.jar:5.3.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.8.jar:5.3.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.8.jar:5.3.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.8.jar:5.3.8]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.8.jar:5.3.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.48.jar:9.0.48]
at java.base/java.lang.Thread.run(Thread.java:832) ~[na:na]
As far as i can tell it needs an order to print them in a page which I already did in the query in the repo.
Please, note that you are importing java.awt.print.Pageable, java.awt.print.PageFormat and java.awt.print.Printable. That could be misleading, because the pagination with Spring Data uses org.springframework.data.domain.Pageable, so I'd change those imports.
Also, a better way to use pagination in the repository is to just pass the pagination configuration using a Pageable, like this:
#Repository
public interface BlogRepository extends JpaRepository<Blog, Long>{
#Query("SELECT b FROM Blog b LEFT JOIN FETCH b.user")
List<Blog> findBlogs(Pageable pageable);
}
This way, you can call the method from the service like this:
#Override
public List<Blog> findLatest5() {
return blogrepo.findBlogs(PageRequest.of(0, 5, Sort.by("date").descending())););
}
I have an error when start my Spring Boot Application: java.lang.IllegalStateException: Expected to be able to resolve a type but got null! This usually stems from types implementing raw Map or Collection interfaces!
I created two tables via sql query:
create table experiment_results
(
id int8 not null,
model jsonb,
train_errors jsonb,
test_errors jsonb,
prediction_error float8,
prediction_result jsonb,
prediction_report_file text,
creation_date timestamp NOT NULL,
PRIMARY KEY (id)
);
create table experiments
(
id int8 not null,
name text not null,
normalized_file text,
normalization_method varchar(255),
normalization_statistic jsonb,
neat_settings jsonb,
columns jsonb,
prediction_window_size int4,
prediction_period int4,
fk_project_id int8 not null,
creation_date timestamp not null,
updated_date timestamp not null,
train_end_index int4,
test_end_index int4,
fk_experiment_result_id int8,
PRIMARY KEY (id)
);
ALTER TABLE if EXISTS experiments add CONSTRAINT project_experiment_fk FOREIGN KEY(fk_project_id) references projects;
ALTER TABLE if EXISTS experiments add CONSTRAINT experiment_reuslt_fk FOREIGN KEY (fk_experiment_result_id) references experiment_results;
After that i created two POJO classes for them:
ExperimentResult:
#Data
#Entity
#NoArgsConstructor
#AllArgsConstructor
#Builder(toBuilder = true)
#Table(name = "experiment_results", schema = "public")
#TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id"
)
public class ExperimentResult {
#Id
#SequenceGenerator(name = "EXPERIMENT_RESULT_ID_GEN", sequenceName = "experiment_result_id_sequence", allocationSize = 1, schema = "public")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EXPERIMENT_RESULT_ID_GEN")
#Column(name = "id")
private Long id;
#Basic
#Column(name = "model", columnDefinition = "jsonb")
#Type(type = "jsonb")
private Map model;
#Column(name = "train_errors", columnDefinition = "jsonb")
#Type(type = "jsonb")
private List<Map<String, Object>> trainErrors;
#Column(name = "test_errors", columnDefinition = "jsonb")
#Type(type = "jsonb")
private List<Map<String, Object>> testErrors;
#Basic
#Column(name = "prediction_error")
private Double predictionError;
#Basic
#Column(name = "creation_date", nullable = false)
private LocalDateTime creationDate;
#Basic
#Column(name = "prediction_reporAt_file")
private String predictionReportFile;
}
Experiment:
#Data
#Entity
#NoArgsConstructor
#AllArgsConstructor
#Builder(toBuilder = true)
#Table(name = "experiments", schema = "public")
#TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id"
)
public class Experiment {
#Id
#SequenceGenerator(name = "EXPERIMENT_ID_GEN", sequenceName = "experiment_id_sequence", allocationSize = 1, schema = "public")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "EXPERIMENT_ID_GEN")
#Column(name = "id")
#JsonView(ExperimentView.Id.class)
private Long id;
#Basic
#Column(name = "name")
#JsonView(ExperimentView.Info.class)
private String name;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "fk_project_id", referencedColumnName = "id", nullable = false)
#JsonIgnore
private Project project;
#Basic
#Column(name = "normalized_file")
#JsonIgnore
private String normalizedDataFile;
#Basic
#Column(name = "normalization_method")
#JsonView(ExperimentView.FullInfo.class)
private String normalizationMethod;
#Basic
#Column(name = "normalization_statistic", columnDefinition = "jsonb")
#Type(type = "jsonb")
#JsonView(ExperimentView.FullInfo.class)
private Map<String, Object> normalization_statistic;
#Basic
#Column(name = "neat_settings", columnDefinition = "jsonb")
#Type(type = "jsonb")
#JsonView(ExperimentView.FullInfo.class)
private List<Map<String, Object>> neatSettings;
#Basic
#Column(name = "columns", columnDefinition = "jsonb")
#Type(type = "jsonb")
#JsonView(ExperimentView.FullInfo.class)
private List<Map<String, Object>> columns;
#Basic
#Column(name = "prediction_window_size")
#JsonView(ExperimentView.FullInfo.class)
private Short predictionWindowSize;
#Basic
#Column(name = "prediction_period")
#JsonView(ExperimentView.FullInfo.class)
private Short predictionPeriod;
#Basic
#Column(name = "creation_date", nullable = false)
#JsonView(ExperimentView.Info.class)
private LocalDateTime creationDate;
#Basic
#Column(name = "updated_date", nullable = false)
#JsonView(ExperimentView.Info.class)
private LocalDateTime updatedDate;
#OneToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "fk_experiment_result_id", referencedColumnName = "id")
private ExperimentResult experimentResult;
}
While application is starting, it fails with stacktrace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'experimentRepository' defined in ru.filippov.neat.repository.ExperimentRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Expected to be able to resolve a type but got null! This usually stems from types implementing raw Map or Collection interfaces!
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1794) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$209/0000000000000000.getObject(Unknown Source) ~[na:na]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:624) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:612) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:51) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:36) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:404) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:361) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:898) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:554) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at ru.filippov.neat.NeatvueApplication.main(NeatvueApplication.java:11) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[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:566) ~[na:na]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.3.4.RELEASE.jar:2.3.4.RELEASE]
Caused by: java.lang.IllegalStateException: Expected to be able to resolve a type but got null! This usually stems from types implementing raw Map or Collection interfaces!
at org.springframework.data.util.TypeInformation.getRequiredActualType(TypeInformation.java:184) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.mapping.model.AbstractPersistentProperty.getActualType(AbstractPersistentProperty.java:286) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.jpa.mapping.JpaPersistentPropertyImpl.getActualType(JpaPersistentPropertyImpl.java:120) ~[spring-data-jpa-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.jpa.mapping.JpaPersistentPropertyImpl.lambda$new$3(JpaPersistentPropertyImpl.java:111) ~[spring-data-jpa-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.jpa.mapping.JpaPersistentPropertyImpl$$Lambda$718/0000000000000000.get(Unknown Source) ~[na:na]
at org.springframework.data.util.Lazy.getNullable(Lazy.java:212) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.util.Lazy.get(Lazy.java:94) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.jpa.mapping.JpaPersistentPropertyImpl.isEntity(JpaPersistentPropertyImpl.java:150) ~[spring-data-jpa-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.mapping.model.AbstractPersistentProperty.getPersistentEntityTypes(AbstractPersistentProperty.java:150) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.jpa.mapping.JpaPersistentPropertyImpl.getPersistentEntityTypes(JpaPersistentPropertyImpl.java:132) ~[spring-data-jpa-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:562) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.doWith(AbstractMappingContext.java:520) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:705) ~[spring-core-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:389) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator$$Lambda$723/0000000000000000.accept(Unknown Source) ~[na:na]
at java.base/java.util.Collections$SingletonSet.forEach(Collections.java:4797) ~[na:na]
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.createAndRegisterProperty(AbstractMappingContext.java:562) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.mapping.context.AbstractMappingContext$PersistentPropertyCreator.doWith(AbstractMappingContext.java:520) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.util.ReflectionUtils.doWithFields(ReflectionUtils.java:705) ~[spring-core-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:389) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:263) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:206) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:90) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$4(RepositoryFactoryBeanSupport.java:295) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport$$Lambda$663/0000000000000000.accept(Unknown Source) ~[na:na]
at java.base/java.util.Optional.ifPresent(Optional.java:183) ~[na:na]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:295) ~[spring-data-commons-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:144) ~[spring-data-jpa-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1853) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1790) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
... 31 common frames omitted
After that i removed ExperimentResult field from Experiment POJO and my application started succesfully. What i'm doing wrong? For example, fk_project_id works fine, but it have #ManyToOne annotation.
JSONB is not directly supported by Hibernate.
You have to use a converter.
There is a collection of converters in Hibernate Types project: https://github.com/vladmihalcea/hibernate-types
The problem was private Map model; in ExperimentResult POJO.
We MUST define generics, for example Map<String, Object> model
I am trying to create a Post API which will add a user to my database.
I have 3 tables:
1: ol__user
2: ol__roles
3: ol__users_roles
There is no relation between ol__user and ol__roles but ol__users_roles contains both table's Ids.
Data Model
I used #jointable annotation and my codes are written below :
#Entity
#Table(name = "ol__user")
#DynamicUpdate
#EntityListeners(AuditingEntityListener.class)
public class ol__user {
#Id
#GeneratedValue(strategy = GenerationType.AUTO,generator = "system-uuid")
#GenericGenerator(name="system-uuid", strategy = "uuid")
#Column(name = "id", unique = true, nullable = false)
private String user_Id;
#Column(name = "username", nullable = true)
private String username;
#Column(name = "password", nullable = false)
private String password;
#Column(name = "salt", nullable = true)
private String salt;
#Column(name = "is_active", nullable = false)
private Boolean is_active;
#Column(name = "create_at", nullable = true)
private Timestamp create_at;
#Column(name = "email", nullable = false)
private String email;
#Column(name = "password_requested_at", nullable = true)
private Timestamp password_requested_at;
#Column(name = "confirmation_token", nullable = true)
private String confirmation_token;
#Column(name = "deleted_at", nullable = true)
private Timestamp deleted_at;
#Column(name = "last_login_at", nullable = true)
private Timestamp last_login_at;
#Column(name = "dtype", nullable = false)
private String dtype;
#Column(name = "temporary_password_set_at", nullable = true)
private Timestamp temporary_password_set_at;
#Column(name = "action_token", nullable = true)
private String action_token;
#Column(name = "referral_customer_email", nullable = true)
private String referral_customer_email;
#Column(name = "newsletter_used_flag", nullable = true)
private Boolean newsletter_used_flag;
#Column(name = "phone", nullable = true)
private String phone;
#Column(name = "status_type", nullable = true)
private String status_type;
#Column(name = "status_state", nullable = true)
private String status_state;
#Column(name = "first_name", nullable = true)
private String first_name;
#Column(name = "last_name", nullable = true)
private String last_name;
#Column(name = "external", nullable = true)
private Boolean external;
#Column(name = "api_key", nullable = true)
private String api_key;
#Column(name = "allow_point_transfer", nullable = true)
private Boolean allow_point_transfer;
#OneToOne(cascade = CascadeType.ALL )
#JoinTable(name="ol__users_roles",
joinColumns =
{#JoinColumn(name="user_id",referencedColumnName = "id")},
inverseJoinColumns =
{#JoinColumn(name="role_id",referencedColumnName = "id")}
)
private ol__roles roles;
public ol__roles getRoles() {
return roles;
}
public void setRoles(ol__roles roles) {
this.roles = roles;
}
setter AND getters..
here is my second table code:
#Entity
#Table(name="ol__roles")
#EntityListeners(AuditingEntityListener.class)
public class ol__roles {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", unique = true, nullable = false)
private Integer roleId;
#Column(name="name",nullable = true)
private String name;
#Column(name="role",nullable = true)
private String role;
#Column(name="is_master",nullable = true)
private Boolean is_master;
setter and getters ...
here is my third table code:
#Entity
#Table(name="ol__users_roles")
#EntityListeners(AuditingEntityListener.class)
public class ol__users_roles {
#Id
#Column(name = "user_id",unique = true,nullable = false)
private String user_id;
#Column(name = "role_id",unique = true,nullable = false)
private Integer role_id;
setter and getters ...
ol__users_roles doesn't have a unique id and just has this 2 foreign keys.
In my Controller, I have this code:
#PostMapping("/admin/data")
public ol__user createUserAdmin(#Valid #RequestBody ol__user ol__user)
{
return userRepository.save(ol__user);
}
whenever I call this API :
{
"username": "adminssroos",
"firstName": "adminsss",
"lastName": "adminssnew",
"email": "nejatianadmhhhs#admin.com",
"phone": "09354006090",
"salt": "123455",
"roles": {
"role_id": "13"
},
"password": "123#123#Mm",
"is_active": true,
"create_at": "2020-03-01",
"dtype": "admin"
}
I got the error below:
> 2020-04-07 02:27:48.628 INFO 13242 --- [nio-8080-exec-1]
> o.s.web.servlet.DispatcherServlet : Completed initialization in
> 10 ms Hibernate:
> select
> nextval ('hibernate_sequence') Hibernate:
> insert
> into
> ol__roles
> (is_master, name, role, id)
> values
> (?, ?, ?, ?) 2020-04-07 02:27:49.157 WARN 13242 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL
> Error: 0, SQLState: 23502 2020-04-07 02:27:49.157 ERROR 13242 ---
> [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR:
> null value in column "role" violates not-null constraint Detail:
> Failing row contains (18, null, null, null). 2020-04-07 02:27:49.175
> ERROR 13242 --- [nio-8080-exec-1] o.h.i.ExceptionMapperStandardImpl
> : HHH000346: Error during managed flush
> [org.hibernate.exception.ConstraintViolationException: could not
> execute statement] 2020-04-07 02:27:49.242 ERROR 13242 ---
> [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] :
> Servlet.service() for servlet [dispatcherServlet] in context with path
> [] threw exception [Request processing failed; nested exception is
> org.springframework.dao.DataIntegrityViolationException: could not
> execute statement; SQL [n/a]; constraint [role]; nested exception is
> org.hibernate.exception.ConstraintViolationException: could not
> execute statement] with root cause
>
> org.postgresql.util.PSQLException: ERROR: null value in column "role"
> violates not-null constraint Detail: Failing row contains (18, null,
> null, null). at
> org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)
> ~[postgresql-42.2.5.jar:42.2.5] at
> org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183)
> ~[postgresql-42.2.5.jar:42.2.5] at
> org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308)
> ~[postgresql-42.2.5.jar:42.2.5] at
> org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)
> ~[postgresql-42.2.5.jar:42.2.5] at
> org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)
> ~[postgresql-42.2.5.jar:42.2.5] at
> org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:143)
> ~[postgresql-42.2.5.jar:42.2.5] at
> org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:120)
> ~[postgresql-42.2.5.jar:42.2.5] at
> com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
> ~[HikariCP-3.2.0.jar:na] at
> com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)
> ~[HikariCP-3.2.0.jar:na] at
> org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)
> ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
> org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3176)
> ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
> org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3690)
> ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
> org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:90)
> ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
> org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
> ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
> org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:478)
> ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
> org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:356)
> ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
> org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
> ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
> org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1454)
> ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
> org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:511)
> ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
> org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3290)
> ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
> org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2486)
> ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
> org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:473)
> ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
> org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:178)
> ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
> org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:39)
> ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
> org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:271)
> ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
> org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:104)
> ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final] at
> org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:532)
> ~[spring-orm-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:746)
> ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:714)
> ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:534)
> ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:305)
> ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
> ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
> ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
> ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
> ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:138)
> ~[spring-data-jpa-2.1.9.RELEASE.jar:2.1.9.RELEASE] at
> org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
> ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
> ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
> ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
> ~[spring-data-commons-2.1.9.RELEASE.jar:2.1.9.RELEASE] at
> org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
> ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
> ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> com.sun.proxy.$Proxy115.save(Unknown Source) ~[na:na] at
> com.Loyalty.OpenLoyalty.Controllers.Ol__userController.createUserAdmin(Ol__userController.java:41)
> ~[classes/:na] at
> java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
> Method) ~[na:na] at
> java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
> ~[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:567) ~[na:na]
> at
> org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
> ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
> ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
> ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)
> ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
> ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
> ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039)
> ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
> ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
> ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908)
> ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
> ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
> ~[tomcat-embed-websocket-9.0.21.jar:9.0.21] at
> org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
> ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109)
> ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
> ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109)
> ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
> ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109)
> ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
> ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109)
> ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
> org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
> ~[na:na] at
> java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
> ~[na:na] at
> org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
> ~[tomcat-embed-core-9.0.21.jar:9.0.21] at
> java.base/java.lang.Thread.run(Thread.java:830) ~[na:na]
I don't know why my API is inserting to ol__roles instead of ol__users_roles, anybody can help me?
I solved your problem. check this out:
ol__roles model:
#Entity
#Table(name="ol__roles")
#EntityListeners(AuditingEntityListener.class)
public class ol__roles {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", unique = true, nullable = false)
private Integer id;
#Column(name="name",nullable = true)
private String name;
#Column(name="role",nullable = true)
private String role;
#Column(name="is_master",nullable = true)
private Boolean is_master;
#JsonIgnore
#ManyToMany(mappedBy="roles",cascade = {CascadeType.MERGE},fetch= FetchType.EAGER)
private Set<ol__user> users = new HashSet<ol__user>();
//getter and setters
}
ol__user model:
#Entity
#Table(name = "ol__user")
#DynamicUpdate
#EntityListeners(AuditingEntityListener.class)
public class ol__user {
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "system-uuid")
#GenericGenerator(name = "system-uuid", strategy = "uuid")
#Column(name = "id", unique = true, nullable = false)
private String id;
#Column(name = "username", nullable = true)
private String username;
#Column(name = "password", nullable = false)
private String password;
#Column(name = "salt", nullable = true)
private String salt;
#Column(name = "is_active", nullable = false)
private Boolean is_active;
#Column(name = "create_at", nullable = true)
private Timestamp create_at;
#Column(name = "email", nullable = false)
private String email;
#Column(name = "password_requested_at", nullable = true)
private Timestamp password_requested_at;
#Column(name = "confirmation_token", nullable = true)
private String confirmation_token;
#Column(name = "deleted_at", nullable = true)
private Timestamp deleted_at;
#Column(name = "last_login_at", nullable = true)
private Timestamp last_login_at;
#Column(name = "dtype", nullable = false)
private String dtype;
#Column(name = "temporary_password_set_at", nullable = true)
private Timestamp temporary_password_set_at;
#Column(name = "action_token", nullable = true)
private String action_token;
#Column(name = "referral_customer_email", nullable = true)
private String referral_customer_email;
#Column(name = "newsletter_used_flag", nullable = true)
private Boolean newsletter_used_flag;
#Column(name = "phone", nullable = true)
private String phone;
#Column(name = "status_type", nullable = true)
private String status_type;
#Column(name = "status_state", nullable = true)
private String status_state;
#Column(name = "first_name", nullable = true)
private String first_name;
#Column(name = "last_name", nullable = true)
private String last_name;
#Column(name = "external", nullable = true)
private Boolean external;
#Column(name = "api_key", nullable = true)
private String api_key;
#Column(name = "allow_point_transfer", nullable = true)
private Boolean allow_point_transfer;
#ManyToMany(cascade = {CascadeType.MERGE})
#JoinTable(name="ol__users_roles",
joinColumns={#JoinColumn(name="user_id")},
inverseJoinColumns={#JoinColumn(name="role_id")})
private Set<ol__roles> roles = new HashSet<ol__roles>();
//getters and setters
}
and that's it! you don't need to define any model for ol__users_roles.
hope this helps you!
you should not define a new table for role_user . this table created when you define #ManyToMany relationship between two table.
If any user has one role (#OneToOne) or some role (#OneToMany), you don't need role_user table .
If a user has some role so in role table created a column as foreign_key.
for excample :
public class user {
private String name ;
//another fields...
#OneToMany(mappedBy = "user", fetch = FetchType.LAZY , cascade = CascadeType.REMOVE)
private Set<Role> roles = new HashSet<>();
//getter & setter
}
public class Role{
private String role;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "role_id")
#JsonIgnore
private User user ;
//getter & setter
}
NOTE : using #JoinTable create new table with to foreign_key.
This question already has answers here:
No serializer found for class org.hibernate.proxy.pojo.javassist.Javassist?
(19 answers)
Closed 3 years ago.
I already went through: Could not write JSON: Infinite recursion (StackOverflowError); nested exception spring boot & many links like this. I am using Spring Boot 2.1.6.RELEASE and Data JPA and Postgres example
This is my source code: https://github.com/JavaHelper/issue-jackson-boot
Error:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.data.domain.PageImpl["content"]->java.util.Collections$UnmodifiableRandomAccessList[0]->com.example.demo.entity.StockDailyRecord["stock"]->com.example.demo.entity.Stock$HibernateProxy$f8byIJ39["hibernateLazyInitializer"])
at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:77) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.SerializerProvider.reportBadDefinition(SerializerProvider.java:1191) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.DatabindContext.reportBadDefinition(DatabindContext.java:313) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:71) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:33) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:727) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:719) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:727) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:719) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:119) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serialize(IndexedListSerializer.java:79) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serialize(IndexedListSerializer.java:18) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:727) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:719) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1396) ~[jackson-databind-2.9.9.jar:2.9.9]
at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:913) ~[jackson-databind-2.9.9.jar:2.9.9]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:287) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:103) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:290) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:225) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:82) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:122) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.21.jar:9.0.21]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109) ~[spring-web-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853) [tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587) [tomcat-embed-core-9.0.21.jar:9.0.21]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.21.jar:9.0.21]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_171]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_171]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.21.jar:9.0.21]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_171]
Stock.java
#Data
#NoArgsConstructor
#AllArgsConstructor
#EqualsAndHashCode(callSuper = true)
#Entity
#Table(name = "stock", uniqueConstraints = { #UniqueConstraint(columnNames = "STOCK_NAME"),
#UniqueConstraint(columnNames = "STOCK_CODE") })
public class Stock extends BaseEntity implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "STOCK_ID", unique = true, nullable = false)
private Integer stockId;
#Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
private String stockCode;
#Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
private String stockName;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "stock")
#JsonBackReference
private Set<StockDailyRecord> stockDailyRecords = new HashSet<>(0);
#Builder(builderMethodName = "sBuilder")
public Stock(Integer stockId, String stockCode, String stockName, Set<StockDailyRecord> stockDailyRecords,
Instant createdDate, Instant lastUpdateDate, String createUser, String lastUpdateUser) {
super(createdDate, lastUpdateDate, createUser, lastUpdateUser);
this.stockId = stockId;
this.stockCode = stockCode;
this.stockName = stockName;
this.stockDailyRecords = stockDailyRecords;
}
}
StockDailyRecord.java
#Data
#NoArgsConstructor
#AllArgsConstructor
#EqualsAndHashCode(callSuper = true)
#Entity
#Table(name = "stock_daily_record")
public class StockDailyRecord extends BaseEntity implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "RECORD_ID", unique = true, nullable = false)
private Integer recordId;
#Column(name = "PRICE_OPEN", precision = 6)
private Float priceOpen;
#Column(name = "PRICE_CLOSE", precision = 6)
private Float priceClose;
#Column(name = "PRICE_CHANGE", precision = 6)
private Float priceChange;
#Column(name = "VOLUME")
private Long volume;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "STOCK_ID", nullable = false)
#JsonManagedReference
private Stock stock;
#Builder(builderMethodName = "sdBuilder")
public StockDailyRecord(Integer recordId, Float priceOpen, Float priceClose, Float priceChange, Long volume,
Stock stock, Instant createdDate, Instant lastUpdateDate, String createUser, String lastUpdateUser) {
super(createdDate, lastUpdateDate, createUser, lastUpdateUser);
this.recordId = recordId;
this.priceOpen = priceOpen;
this.priceClose = priceClose;
this.priceChange = priceChange;
this.volume = volume;
this.stock = stock;
}
}
BaseEntity.java
#Data
#NoArgsConstructor
#AllArgsConstructor
#MappedSuperclass
#EntityListeners(AuditingEntityListener.class)
public class BaseEntity {
#CreatedDate
#Column(name = "createdDate", nullable = false, updatable = false)
private Instant createdDate;
#LastModifiedDate
#Column(name = "lastUpdateDate", nullable = false)
private Instant lastUpdateDate;
#Column(name = "createUser", nullable = false, length = 50)
private String createUser;
#Column(name = "lastUpdateUser", length = 50)
private String lastUpdateUser;
}
Not sure how this is working, but mixed of two things are working nicely. Took reference from here: Great Link
I added both #JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) and #JsonIgnore Can not preserve the Bidirectional-Relationships after deserialization.
Here is my class now
#Data
#NoArgsConstructor
#AllArgsConstructor
#EqualsAndHashCode(callSuper = true)
#Entity
#Table(name = "stock", uniqueConstraints = { #UniqueConstraint(columnNames = "STOCK_NAME"),
#UniqueConstraint(columnNames = "STOCK_CODE") })
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Stock extends BaseEntity implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "STOCK_ID", unique = true, nullable = false)
private Integer stockId;
#Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
private String stockCode;
#Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
private String stockName;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "stock")
#JsonIgnore
private Set<StockDailyRecord> stockDailyRecords = new HashSet<>(0);
#Builder(builderMethodName = "sBuilder")
public Stock(Integer stockId, String stockCode, String stockName, Set<StockDailyRecord> stockDailyRecords,
Instant createdDate, Instant lastUpdateDate, String createUser, String lastUpdateUser) {
super(createdDate, lastUpdateDate, createUser, lastUpdateUser);
this.stockId = stockId;
this.stockCode = stockCode;
this.stockName = stockName;
this.stockDailyRecords = stockDailyRecords;
}
}
Note: Since it's #ManyToOne Relationship, so we cant not excepts StockDailyRecord from Stock, it will always be like getting Stock data from StockDailyRecord
You can also look Here
This is great: My Here
You might ignore properties hibernateLazyInitializer and handler, well this issue is when you have entities that are loaded lazily before the serialization then the entities get loaded fully. Put on the head of class that causes this issue.
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})