could not deserialize] with root cause java.io.EOFException: null - java

I have seen some questions on this subject but I have not got any valid solution for my case
I'm having an exception with jason serialization I have the following classes
when I do a GET Pacientes I have an exception of the serialization privilege type
2017-11-14 08:54:35.039 INFO 8724 --- [nio-8080-exec-1] o.h.e.internal.DefaultLoadEventListener : HHH000327: Error performing load command : org.hibernate.type.SerializationException: could not deserialize
2017-11-14 08:54:35.047 ERROR 8724 --- [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.orm.jpa.JpaSystemException: could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize] with root cause
java.io.EOFException: null
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source) ~[na:1.8.0_144]
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source) ~[na:1.8.0_144]
at java.io.ObjectInputStream.readStreamHeader(Unknown Source) ~[na:1.8.0_144]
at java.io.ObjectInputStream.<init>(Unknown Source) ~[na:1.8.0_144]
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:309) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:299) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:218) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
I'm using framwork Spring boot with spring data jpa
class Paciente
import java.io.Serializable;
import java.math.BigInteger;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import digifred.model.global.Entidades;
import digifred.model.global.IdentidadesGenero;
import digifred.model.global.OrientacoesSexuais;
import digifred.model.global.Pessoas;
#Entity
#Table(name = "pacientes", schema = "sau")
public class Pacientes implements Serializable {
private static final long serialVersionUID = 5776384003601026304L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idPaciente")
private Long idPaciente;
#JoinColumn(name="id_entidade")
#ManyToOne(cascade = CascadeType.ALL)
private Entidades entidade;
#Basic(optional = false)
#JoinColumn(name="idPessoa")
#ManyToOne(cascade = CascadeType.ALL)
private Pessoas pessoa;
#Column(name = "idResponsavel_familiar")
private BigInteger responsavelFamiliar;
#Column(name = "nomeResponsavel")
private String nomeResponsavel;
#Column(name = "cpfResponsavel")
private String cpfResponsavel;
#Column(name = "cnsResponsavel")
private String cnsResponsavel;
#Column(name = "flagAlergico")
private Integer flagAlergico;
#Column(name = "observacoesAlergias")
private String observacoesAlergias;
#Column(name = "microarea")
private String microarea;
#Column(name = "idDomicilio")
private Long idDomicilio;
#JoinColumn(name="idOrientacaoSexual")
#ManyToOne
private OrientacoesSexuais orientacaoSexual;
#JoinColumn(name="idIdentidadeGenero", insertable=false, updatable=false)
#ManyToOne
private IdentidadesGenero identidadeGenero;
#Basic(optional = false)
#Column(name = "flag_ativo")
private int flagAtivo;
#JoinColumn(name="idArea")
#ManyToOne
private Areas area;
#JoinColumn(name="idFamilia")
#ManyToOne
private Familias familia;
public Pacientes() {
}
getters and setters
}

Looks like you're trying to deserialize an empty stream.

You can’t simply transfer database entities over a REST interface, you have to create DTOs and transfer them instead of your entities.

For me, the cause was using #Column instead of #JoinColumn on an association. Was able to find out by turning on logging for the queries being run:
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.springframework.transaction=DEBUG
logging.level.org.hibernate=DEBUG
logging.level.org.hibernate.SQL=debug
logging.level.org.hibernate.type.descriptor.sql=trace
tbh, not sure which of those properties are actually needed, but I found them on some other SO question and just turn them all on when debugging. In the logs I saw a line for each of the columns that were fetched and the last one logged before the exception I was getting was the column value for the association where I had the wrong annotation.

Related

How can I bring a large entity and convert the same to dto using Spring Boot [duplicate]

This question already has answers here:
How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session
(24 answers)
Closed last year.
I'm trying to make a database based API I have a huge load of data but every time I try to bring the data even with pageable property I get this error:
{
"timestamp": "2022-01-12T01:34:01.851+00:00",
"status": 500,
"error": "Internal Server Error",
"trace": "org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: br.com.leomanzini.space.flight.news.model.Article.launches, could not initialize proxy - no Session\r\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:612)\r\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:218)\r\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:591)\r\n\tat org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:149)\r\n\tat org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:387)\r\n\tat java.base/java.lang.Iterable.forEach(Iterable.java:74)\r\n\tat br.com.leomanzini.space.flight.news.dto.ArticlesDTO.<init>(ArticlesDTO.java:65)\r\n\tat br.com.leomanzini.space.flight.news.service.ArticleService.lambda$findAll$0(ArticleService.java:30)\r\n\tat java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)\r\n\tat java.base/java.util.ArrayList$Itr.forEachRemaining(ArrayList.java:1032)\r\n\tat java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)\r\n\tat java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)\r\n\tat java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)\r\n\tat java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)\r\n\tat java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)\r\n\tat java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)\r\n\tat org.springframework.data.domain.Chunk.getConvertedContent(Chunk.java:173)\r\n\tat org.springframework.data.domain.PageImpl.map(PageImpl.java:106)\r\n\tat br.com.leomanzini.space.flight.news.service.ArticleService.findAll(ArticleService.java:30)\r\n\tat br.com.leomanzini.space.flight.news.controller.SpaceFlightsApiController.findAll(SpaceFlightsApiController.java:28)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:566)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:655)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:764)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)\r\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)\r\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)\r\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)\r\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)\r\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)\r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)\r\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\r\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)\r\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1732)\r\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\r\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)\r\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)\r\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n\tat java.base/java.lang.Thread.run(Thread.java:834)\r\n",
"message": "failed to lazily initialize a collection of role: br.com.leomanzini.space.flight.news.model.Article.launches, could not initialize proxy - no Session",
"path": "/articles"
}
At the database I have an amount of 11795 articles and their respectives relationship with others tables, there is a way to optimize this load or just make it works?
Article entity:
import lombok.*;
import javax.persistence.*;
import java.util.List;
#Entity
#Data
#Builder
#NoArgsConstructor
#AllArgsConstructor
#Table(name = "article")
public class Article {
#Id
#EqualsAndHashCode.Include
private Long id;
#Column(nullable = false)
private Boolean featured;
#Column(nullable = false)
private String title;
#Column(nullable = false)
private String url;
#Column(name = "image_url", nullable = false)
private String imageUrl;
#Column(name = "news_site", nullable = false)
private String newsSite;
#Column(nullable = false)
private String summary;
#Column(name = "published_at", nullable = false)
private String publishedAt;
#ManyToMany(fetch = FetchType.LAZY)
private List<Launches> launches;
#ManyToMany(fetch = FetchType.LAZY)
private List<Events> events;
#Column(name = "inserted_by_human")
private Boolean insertedByHuman = false;
}
Events and Launches entities:
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
#Data
#Builder
#NoArgsConstructor
#AllArgsConstructor
public class Events {
#Id
#EqualsAndHashCode.Include
private Long id;
private String provider;
}
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
#Data
#Builder
#NoArgsConstructor
#AllArgsConstructor
public class Launches {
#Id
#EqualsAndHashCode.Include
private String id;
private String provider;
}
The repository is just a interface with JpaRepository and the Article as entity.
The service class:
import br.com.leomanzini.space.flight.news.dto.ArticlesDTO;
import br.com.leomanzini.space.flight.news.model.Article;
import br.com.leomanzini.space.flight.news.repository.ArticleRepository;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
#Service
#AllArgsConstructor
public class ArticleService {
#Autowired
private final ArticleRepository articleRepository;
public Page<ArticlesDTO> findAll(Pageable pageable) {
Page<Article> articleList = articleRepository.findAll(pageable);
return articleList.map(article -> new ArticlesDTO(article));
}
}
If I just use my entity as a return, the methods work, but when I convert the same to dto the application breaks. The dto class is below:
import br.com.leomanzini.space.flight.news.model.Article;
import lombok.*;
import javax.management.ConstructorParameters;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
#Data
#Builder
#NoArgsConstructor
#AllArgsConstructor
public class ArticlesDTO implements Serializable {
#NotEmpty
#EqualsAndHashCode.Include
private Long id;
#NotEmpty
private String title;
#NotEmpty
private String url;
#NotEmpty
private String imageUrl;
#NotEmpty
private String newsSite;
#NotEmpty
private String summary;
#NotEmpty
private String publishedAt;
#NotEmpty
private String updatedAt;
#NotEmpty
private Boolean featured;
#Valid
private List<LaunchesDTO> launches;
#Valid
private List<EventsDTO> events;
public ArticlesDTO (Article article) {
id = article.getId();
title = article.getTitle();
url = article.getUrl();
imageUrl = article.getImageUrl();
newsSite = article.getNewsSite();
summary = article.getSummary();
publishedAt = article.getPublishedAt();
updatedAt = article.getPublishedAt();
featured = article.getFeatured();
launches = new ArrayList<>();
article.getLaunches().forEach(launch -> {
LaunchesDTO launchesDTO = new LaunchesDTO(launch.getId(), launch.getProvider());
launches.add(launchesDTO);
});
events = new ArrayList<>();
article.getEvents().forEach(event -> {
EventsDTO eventsDTO = new EventsDTO(event.getId(), event.getProvider());
events.add(eventsDTO);
});
}
}
There is anyway to fix the error and make it works? Something to accelerate the database load or something else?
With FetchType.LAZY, the query that is used for retrieving those fields will be executed only when it is accessed for the first time. In order to do this, Hibernate creates and configures proxy classes for our entity classes (that's why we also should not declare our entity classes to be final if we want to use the lazy load feature).
When Hibernate initializes proxies, it requires a Session in order to do the task. That's why when you don't add the #Transactional annotation to the service method, it will throw out an LazyInitializationException...no Session.
Beside the solution above, if you don't want to add the #Transactional annotation, you can set hibernate.enable_lazy_load_no_trans property to true.
<property
name="hibernate.enable_lazy_load_no_trans"
value="true"/>
But this solution is considered to be an anti-pattern. It will create a new Session everytime you try to lazy-load. You can read it more here. The hibernate.enable_lazy_load_no_trans Anti-Pattern
The proposed answer was that in the service class, the #Transactional(readOnly = true) attribute has been enabled, it works fine to resolve the error
failed to lazyly initialize a collection of role: br.com .
leomanzini.space.flight.news.model.Article.launches, could not
initialize proxy.
The method at service class looked like this:
import br.com.leomanzini.space.flight.news.dto.ArticlesDTO;
import br.com.leomanzini.space.flight.news.model.Article;
import br.com.leomanzini.space.flight.news.repository.ArticleRepository;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
#AllArgsConstructor
public class ArticleService {
#Autowired
private final ArticleRepository articleRepository;
#Transactional(readOnly = true)
public Page<ArticlesDTO> findAll(Pageable pageable) {
Page<Article> articleList = articleRepository.findAll(pageable);
return articleList.map(article -> new ArticlesDTO(article));
}
}
And the requisition working fine!

could not execute statement; SQL [n/a]; constraint [email_address\" of relation \"users]; nested exception

I'm getting this error while adding to the candidates table.candidates table extends the users table. Email and password columns come from this table.I think there is a problem with the database, I am using postreSql. What would be the reason ?
User Table
package com.example.hrmsdemo.entities.concretes;
import com.sun.istack.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
#Data
#Entity
#AllArgsConstructor
#NoArgsConstructor
#Table(name="users",uniqueConstraints = {#UniqueConstraint(columnNames = {"email"})})
#Inheritance(strategy = InheritanceType.JOINED)
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#NotNull
private int id;
#Column(name = "email")
#NotNull
private String email;
#NotNull
#Column(name = "password")
private String password;
}
Candidate Table
package com.example.hrmsdemo.entities.concretes;
import com.sun.istack.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import java.util.Date;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Table(name="candidates",uniqueConstraints = {#UniqueConstraint(columnNames = {"identity_number"})})
#EqualsAndHashCode(callSuper = true)
#Entity
public class Candidate extends User {
#Column(name = "first_name")
#NotNull
private String first_name;
#NotNull
#Column(name = "last_name")
private String last_name;
#NotNull
#Column(name = "identity_number")
private String identity_number;
#NotNull
#DateTimeFormat(pattern = "yyyy-MM-dd")
#Column(name = "birth_date")
private Date birth_date;
}
Error
2021-05-26 15:59:53.230 WARN 24964 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 23502
2021-05-26 15:59:53.230 ERROR 24964 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : HATA: null value in column "email_address" of relation "users" violates not-null constraint
Ayrıntı: Hata veren satır (7, null, 123414, veyselhim#gmail.com) içeriyor.
2021-05-26 15:59:53.245 ERROR 24964 --- [nio-8080-exec-3] 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 [email_address" of relation "users]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
I assume you really map User#email to a column named email_address? That is the column that the database is complaining about but you do not show a mapping to that column.
Assuming that is true, you have defined that this attribute should be non-null which also seems to be how the database is defined. This would suggest that you are trying to save a User and did not set its email property.
Or maybe you really have not mapped that column and so Hibernate never tries to write to it. Hard to tell from just what you have given us.

How to fix "java.sql.SQLSyntaxErrorException: Unknown column 'product0_.return_policy' in 'field list' " exception?

I've been getting this "SQLSyntaxErrorException:Unknown column 'product0_.return_policy' in 'field list'" when I try to run the URL on my browser to GET all the products.
Look here
The browser shows the below as well:
There was an unexpected error (type=Internal Server Error, status=500).
could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
returnPolicy is the only variable that's causing this problem. I'm able to successfully retrieve all the values from the database when I remove the variable itself from both the database and from the Product class in Java.
This is the getAllProducts method that is part of the RESTController:
#RequestMapping(method=RequestMethod.GET, value="/products")
public List<Product> getAllProducts() {
return productService.getAllProducts();
}
which works fine when I remove the returnPolicy variable altogether.
This is the MySQL table description:
Values stored in returnPolicy column:
returnPolicy
0
0
1
1
1
This is the code for the 'Product' model's variables:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="product")
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private int price;
private String vendor;
private String description;
private Boolean returnPolicy;
ProductRepository
#Repository public interface ProductRepository extends JpaRepository<Product, String>{ }
Is there a problem with the mapping between SQL tinyint(Boolean) and the Boolean type of Java?
Hibernate is assuming that the entity field returnPolicy corresponds to the table column return_policy. But actually, the column name is returnPolicy
Hibernate follows a naming strategy as to what column name should it derive from entity field names. You should explicitly specify whether to use ImplicitNamingStrategy or PhysicalNamingStrategy. Hibernate provides out of the box classes for this.
Alternatively, for this specific issue, annotating the field with explicit column name will make is understand.
See this SO answer for more.
Your returnPolicy is not mapped with column return_policy you can quick fix this with following
Method1
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private int price;
private String vendor;
private String description;
#Column(name = "return_policy")
private Boolean returnPolicy;
Method2
#JsonNaming annotation is manage naming strategy as to what column name should it derive from entity field names.
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
#JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private int price;
private String vendor;
private String description;
private Boolean returnPolicy;
You can use this annotation #Transient if you don't use attribute as column in database
#Transient annotation in JPA or Hibernate is used to indicate that a field is not to be persisted or ignore fields to save in the database. #Transient exist in javax. persistence package. It is used to annotate a property or field of an entity class, mapped superclass, or embeddable class.
You can use it in this way .
#Transient
private String token;
Hibernate converts the camel case lettering to underscores by default. so you either change your columns in your table to reflect that or change hibernate naming strategy.
Add the below in the application.properties file:
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

could not extract ResultSet when inserting record into database using Spring Boot

I am trying to do a simple insertion into my database using Spring boot. When I run my program, I get the error 'could not extract ResultSet'. But I am not looking to extract anything out, I am just purely inserting.
This is my model code:
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
#Entity(name = "calendar")
#Table(name = "TB_EVENT")
public class Calendar {
#Id
#GeneratedValue
#JoinColumn(name = "EventID")
private int eventId;
#JoinColumn(name = "Privacy")
private String privacy;
#JoinColumn(name = "EventCode")
private String eventCode;
#JoinColumn(name = "Subject")
private String subject;
#JoinColumn(name = "Location")
private String location;
My service implementation class:
#Override
public void add(Calendar calendar) {
// TODO Auto-generated method stub
logger.info("invoked insertevent function in calendarServiceImpl");
logger.info(calendar.getPrivacy());
logger.info(calendar.getAllDay());
logger.info(calendar.getEventCode());
logger.info(calendar.getSubject());
logger.info(calendar.getReminder());
logger.info(calendar.getLocation());
logger.info(calendar.getStartTime());
logger.info(calendar.getEndTime());
logger.info(calendar.getRecur());
logger.info(calendar.getRemarks());
calendarRepository.save(calendar);
}
I am using the .save() and in my database I have set the id to be auto incremental. Anybody know what went wrong?
Thanks guys, I managed to solve the problem by adding #GeneratedValue(strategy = GenerationType.IDENTITY)
Try to change annotations above fields to #Column.
#JoinColumn is used to indicate the relationship and ownership of the relationship. I guess what you need is #Column annotation.
So replace all #JoinColumn's with #Column would fix the problem.
To see what #JoinColumn does please refer
Using #JoinColumn instead of #Column is first issue that anyone can see from sky high. Please change it to #Column as Hibernate docs suggest. Putting #JoinColumn does not map your field to database in any situation whatsoever.
Also "could not extract ResultSet" is not helpful at all you should have posted your stacktrace instead of only few words.

JPQL (Hibernate implementation) select with join issues

I'm having a bit of a rough time with JPQL (using Hibernate).
I have 2 Entities:
package org.oscarehr.common.model;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.JoinColumn;
import javax.persistence.CascadeType;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
#Entity
#Table(name="spireAccessionNumberMap")
public class SpireAccessionNumberMap extends AbstractModel<Integer> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name="uaccn")
private Integer uaccn;
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JoinColumn(name="uaccn_id", referencedColumnName="id")
private List<SpireCommonAccessionNumber> commonAccessionNumbers = new ArrayList<SpireCommonAccessionNumber>();
public SpireAccessionNumberMap() {
}
public SpireAccessionNumberMap(Integer uniqueAccn) {
this.uaccn = uniqueAccn;
}
//#Override
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUniqueAccessionNumber() {
return uaccn;
}
public void setUniqueAccessionNumber(Integer uaccn) {
this.uaccn = uaccn;
}
public List<SpireCommonAccessionNumber> getCommonAccessionNumbers() {
return commonAccessionNumbers;
}
#PrePersist
public void prePersist() {
Iterator<SpireCommonAccessionNumber> i = this.commonAccessionNumbers.iterator();
SpireCommonAccessionNumber commonAccessionNumber;
while(i.hasNext()) {
commonAccessionNumber = i.next();
commonAccessionNumber.setUniqueAccessionId(this.uaccn);
}
}
}
and
package org.oscarehr.common.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
#Entity
#Table(name="spireCommonAccessionNumber")
public class SpireCommonAccessionNumber extends AbstractModel<Integer> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name="caccn")
private String caccn;
#ManyToOne
#JoinColumn(name="uaccn_id", referencedColumnName="id")
private Integer uaccn_id;
//#Override
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCommonAccessionNumber() {
return caccn;
}
public void setCommonAccessionNumber(String caccn) {
this.caccn = caccn;
}
public Integer getUniqueAccessionId() {
return uaccn_id;
}
public void setUniqueAccessionId(Integer uaccn_id) {
this.uaccn_id = uaccn_id;
}
}
Basically, I have the 'map' object, which has a unique number associated with it. The map object has a 'link' to 1 or more 'commonNumber' objects, which store a 'common' number.
The idea is to be able to map lots of common numbers to a unique number using the JPQL and 'Dao's.
However, when I deploy my java WAR file, I get this error:
2013-01-04 13:42:12,344 INFO [Version:14] Hibernate Commons Annotations 3.1.0.GA
2013-01-04 13:42:12,347 INFO [Version:16] Hibernate EntityManager 3.4.0.GA
2013-01-04 13:42:17,753 ERROR [ContextLoader:215] Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [spring_jpa.xml]: Invocati
on of init method failed; nested exception is org.hibernate.AnnotationException: #OneToOne or #ManyToOne on org.oscarehr.common.model.SpireCommonAccessionNumber.uaccn_
id references an unknown entity: java.lang.Integer
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:567)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.oscarehr.common.web.OscarSpringContextLoader.createWebApplicationContext(OscarSpringContextLoader.java:97)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4206)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:601)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:943)
at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:778)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:504)
at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1385)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:306)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1389)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1653)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1662)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1642)
at java.lang.Thread.run(Thread.java:679)
Caused by: org.hibernate.AnnotationException: #OneToOne or #ManyToOne on org.oscarehr.common.model.SpireCommonAccessionNumber.uaccn_id references an unknown entity: java.lang.Integer
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:81)
at org.hibernate.cfg.AnnotationConfiguration.processEndOfQueue(AnnotationConfiguration.java:456)
at org.hibernate.cfg.AnnotationConfiguration.processFkSecondPassInOrder(AnnotationConfiguration.java:438)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:309)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1148)
at org.hibernate.ejb.Ejb3Configuration.buildMappings(Ejb3Configuration.java:1226)
at org.hibernate.ejb.EventListenerConfigurator.configure(EventListenerConfigurator.java:173)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:854)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:425)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:131)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:257)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
... 28 more
I'm at a bit of a loss here...I've tried fiddling around with different ways to map the 'common' object to the 'map' object, but I keep getting errors.
Would anyone be able to shed some light on this for me?
The mapping for the #ManyToOne seems like it should be.
#ManyToOne()
#JoinColumn(name="uaccn_id")
private SpireAccessionNumberMap spireAccessionNumberMap;
public SpireAccessionNumberMap getSpireAccessionNumberMap() {
return spireAccessionNumberMap;
}
public void setSpireAccessionNumberMap(
SpireAccessionNumberMap spireAccessionNumberMap) {
this.spireAccessionNumberMap = spireAccessionNumberMap;
}
The OneToMany side needs the following mapping.
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER,mappedBy="spireAccessionNumberMap")
private List<SpireCommonAccessionNumber> commonAccessionNumbers = new ArrayList<SpireCommonAccessionNumber>();

Categories