54

Any ideas as to how I could resolve this error? I am using Spring JPA with Hibernate. Necessary details below.

Entity class 1:

@Entity
@Table(name = "ways")
@TypeDef(name = "hstore", typeClass = HstoreUserType.class)
@Cacheable
public class Way {

    /**
     * Primary key for the row in table.
     */
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    /**
     * The ID to represent it across the system.
     * Used for preserving historical information. 
     */
    @Column(name = "way_id")
    private Long wayId;

    /**
     * The version of the way this Object represents. 
     */
    @Column(name = "version")
    private Integer version;


    /**
     * The {@link User} that edited this version. 
     */
    @OneToOne
    @PrimaryKeyJoinColumn(name = "user_id")
    private User user;

    /**
     * Timestamp when this version of the Way was edited.
     */
    @Column(name = "tstamp")
    @Temporal(TemporalType.TIMESTAMP)
    private Date timestamp;

    /**
     * The changeset that this version of the way belongs to. 
     */
    @Column(name = "changeset_id")
    private Long changesetId;

    /**
     * All the tags this Way contains. 
     */
    @Type(type = "hstore")
    @Column(name = "tags", columnDefinition = "hstore")
    private Object2ObjectOpenHashMap<String, String> tags = new Object2ObjectOpenHashMap<String, String>(); 

    @Column(name = "bbox")
    private Geometry bbox;

    @Column(name = "linestring")
    private Geometry linestring;

    @Column(name = "nodes")
    private Long[] nodes;

    // getters and setters
}

Entity class for User:

@Entity
@Table(name = "users")
@Cacheable
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @Column(name = "name", unique = true)
    private String name;

    // getters and setters

}

And the stacktrace :

The stacktrace is quite huge. I am pasting the whole stacktrace below for reference and a quick TL;DR here:

javax.persistence.PersistenceException: org.hibernate.type.SerializationException: could not deserialize
Caused by: org.hibernate.type.SerializationException: could not deserialize
Caused by: java.io.StreamCorruptedException: invalid stream header: 30313033

Full stacktrace follows:

javax.persistence.PersistenceException: org.hibernate.type.SerializationException: could not deserialize
        at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1361)
        at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1289)
        at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:261)
        at org.hibernate.ejb.criteria.CriteriaQueryCompiler$3.getResultList(CriteriaQueryCompiler.java:260)
        at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:250)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFac
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySuppo
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeReava:92)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
        at com.sun.proxy.$Proxy36.findAll(Unknown Source)
        at com.osmrecommend.persistence.service.WayPersistenceServiceImpl.getAllWays(WayPersistenceServiceImpl.java:32)
        at com.osmrecommend.dao.WayDAO.getAllWays(WayDAO.java:37)
        at com.osmrecommend.cbf.TFIDFModelBuilder.get(TFIDFModelBuilder.java:90)
        at com.osmrecommend.cbf.TFIDFModelBuilder.get(TFIDFModelBuilder.java:36)
        at org.grouplens.grapht.util.MemoizingProvider.get(MemoizingProvider.java:59)
        at org.grouplens.lenskit.inject.StaticInjector.instantiate(StaticInjector.java:130)
        at org.grouplens.lenskit.inject.StaticInjector.apply(StaticInjector.java:137)
        at org.grouplens.lenskit.inject.StaticInjector.apply(StaticInjector.java:47)
        at org.grouplens.lenskit.eval.traintest.ComponentCache$NodeInstantiator.call(ComponentCache.java:166)
        at com.google.common.cache.LocalCache$LocalManualCache$1.load(LocalCache.java:4792)
        at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3599)
        at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2379)
        at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2342)
        at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2257)
        at com.google.common.cache.LocalCache.get(LocalCache.java:4000)
        at com.google.common.cache.LocalCache$LocalManualCache.get(LocalCache.java:4789)
        at org.grouplens.lenskit.eval.traintest.ComponentCache$Instantiator.apply(ComponentCache.java:126)
        at org.grouplens.lenskit.eval.traintest.ComponentCache$Instantiator.apply(ComponentCache.java:104)
        at org.grouplens.lenskit.inject.RecommenderInstantiator$1.apply(RecommenderInstantiator.java:109)
        at org.grouplens.lenskit.inject.RecommenderInstantiator$1.apply(RecommenderInstantiator.java:99)
        at org.grouplens.lenskit.inject.RecommenderInstantiator.replaceShareableNodes(RecommenderInstantiator.java:188)
        at org.grouplens.lenskit.inject.RecommenderInstantiator.instantiate(RecommenderInstantiator.java:99)
        at org.grouplens.lenskit.eval.traintest.LenskitEvalJob.buildRecommender(LenskitEvalJob.java:74)
        at org.grouplens.lenskit.eval.traintest.TrainTestJob.runEvaluation(TrainTestJob.java:117)
        at org.grouplens.lenskit.eval.traintest.TrainTestJob.call(TrainTestJob.java:101)
        at org.grouplens.lenskit.eval.traintest.JobGraph$JobNode.call(JobGraph.java:116)
        at org.grouplens.lenskit.eval.traintest.JobGraph$JobNode.call(JobGraph.java:102)
        at org.grouplens.lenskit.util.parallel.SequentialTaskGraphExecutor.execute(SequentialTaskGraphExecutor.java:37)
        at org.grouplens.lenskit.eval.traintest.TrainTestEvalTask.runEvaluations(TrainTestEvalTask.java:468)
        at org.grouplens.lenskit.eval.traintest.TrainTestEvalTask.perform(TrainTestEvalTask.java:398)
        at org.grouplens.lenskit.eval.traintest.SimpleEvaluator.call(SimpleEvaluator.java:313)
        at com.osmrecommend.app.OSMRecommendEval.main(OSMRecommendEval.java:94)
Caused by: org.hibernate.type.SerializationException: could not deserialize
        at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:262)
        at org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:306)
        at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:131)
        at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:117)
        at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:39)
        at org.hibernate.type.descriptor.sql.VarbinaryTypeDescriptor$2.doExtract(VarbinaryTypeDescriptor.java:67)
        at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:65)
        at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:269)
        at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:265)
        at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:238)
        at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:357)
        at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2695)
        at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1552)
        at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1484)
        at org.hibernate.loader.Loader.getRow(Loader.java:1384)
        at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:640)
        at org.hibernate.loader.Loader.doQuery(Loader.java:856)
        at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:289)
        at org.hibernate.loader.Loader.doList(Loader.java:2463)
        at org.hibernate.loader.Loader.doList(Loader.java:2449)
        at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2279)
        at org.hibernate.loader.Loader.list(Loader.java:2274)
        at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:470)
        at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355)
        at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:196)
2014-04-13 17:35:49 INFO  persistence.service.WayPersistenceServiceImpl:37 - All ways fetched in 331s
        at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1115)
        at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
        at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:252)
        ... 51 more
Caused by: java.io.StreamCorruptedException: invalid stream header: 30313033
        at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:804)
        at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
        at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:328)
        at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:318)
        at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:237)
        ... 78 more

UPDATE:

I updated the Ways entity class to the following, but error still occurs :

@Entity
@Table(name = "ways")
@Cacheable
public class Way implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -7941769011539363185L;

    /**
     * Primary key for the row in table.
     */
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    /**
     * The ID to represent it across the system.
     * Used for preserving historical information. 
     */
    @Column(name = "way_id")
    private Long wayId;

    /**
     * The version of the way this Object represents. 
     */
    @Column(name = "version")
    private Integer version;


    /**
     * The {@link User} that edited this version. 
     */
    @OneToOne
    @PrimaryKeyJoinColumn(name = "user_id")
    private User user;

    /**
     * Timestamp when this version of the Way was edited.
     */
    @Column(name = "tstamp")
    @Temporal(TemporalType.TIMESTAMP)
    private Date timestamp;

    /**
     * The changeset that this version of the way belongs to. 
     */
    @Column(name = "changeset_id")
    private Long changesetId;

    /**
     * All the tags this Way contains. 
     */
    @Column(name = "tags")
    private String tags; 

    @Column(name = "bbox")
    private Geometry bbox;

    @Column(name = "linestring")
    private Geometry linestring;

    @Column(name = "nodes")
    @ElementCollection(targetClass=Long.class)
    private List<Long> nodes;
15
  • 2
    30313033 in hex is 0103. Does that ring any bells? You are deserializing something that wasn't actually serialized, and appears to be a number in string format.
    – user207421
    Commented Apr 13, 2014 at 23:07
  • That doesn't really ring any bells. Is there any way of knowing what that something might be?
    – bcosynot
    Commented Apr 13, 2014 at 23:15
  • That sounds like you changed the class definition and tried to deserialize data serialized from previous version of the class
    – gerrytan
    Commented Apr 13, 2014 at 23:20
  • @gerrytan No it doesn't. That would give a different exception.
    – user207421
    Commented Apr 13, 2014 at 23:27
  • 2
    This problem sounds a little bit weird. my suggestion is to remove the objects in use in your entity ex: (Geometry, User) one by one and check whether the problem is going to be solve or not ... if It didn't solve out, at least you will understand that the problem is for something else ...
    – Mehdi
    Commented Apr 22, 2014 at 5:38

17 Answers 17

76

For others with the same error (does not answer this exact question)

I experienced this error with hibernate 4.3 and 5.0.5 due to fields of type java.time.LocalDateTime, I have several entities using LocalDateTime, but only one of them caused the issue, I don't know why.

It was fixed by adding the following dependency:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-java8</artifactId>
    <version>${hibernate.version}</version>
</dependency>
2
  • 1
    I was using "spring-boot-starter-data-jpa" and it depends on hibernate 5.0.11. Changing the dependency solved the problem. (and I won't use spring starter dependencies (: ) Thanks a lot. Commented Dec 15, 2016 at 11:07
  • I suspect Spring Boot is part of the problem here with the dependencies it is pulling in.
    – jediwompa
    Commented Feb 19, 2021 at 17:52
39
+50

This issue is happening when something cannot be deserialized (thank you, Captain Obvious). In your entity mappings the following looks suspicious:

@Type(type = "hstore")
@Column(name = "tags", columnDefinition = "hstore")
private Object2ObjectOpenHashMap<String, String> tags = new Object2ObjectOpenHashMap<String, String>(); 

@Column(name = "bbox")
private Geometry bbox;

@Column(name = "linestring")
private Geometry linestring;

My suggestion is either to take a look over Geometry and Object2ObjectHashMap classes - check whether they are serializable itself and all their fields either serializable too, or marked with transient keyword. Also if you post these classes here, this may help aswell. HstoreUserType class listing may also be helpful.

4
  • Updated the entity code to use more general data types. The `Geometry' data type and all of its fields are serializable.
    – bcosynot
    Commented Apr 16, 2014 at 13:53
  • 1
    Can you try to remove Geometry references from the mappings, just for the experiment and recheck whether the problem is still here? Commented Apr 16, 2014 at 13:57
  • @vr3690 Thanks for bounty reward :) Can I ask you to do some post/comments updates about the problem cause and its solution? Commented Apr 24, 2014 at 6:31
  • @Alexey Malev Can you show an example of serializing a Geometry?
    – horoyoi o
    Commented Feb 4, 2020 at 4:36
17

Regarding the kaba713 answer and converting java.time.* by Hibernate.

I use org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters; and it works with Spring-Boot 1.5.4.

@Column(name = "order_date", nullable = false)
@Convert(converter = Jsr310JpaConverters.LocalDateTimeConverter.class)
private LocalDateTime orderDate;

And we don't need to write a custom converter.

0
9

The problem should be for the Geometry relation, it is mapped as a regular column so Hibernate try to map a simple Column to a Geometry object. I had a similar problem and the solution was to explicity define the relation, something like:

@OneToOne
@JoinColumn(name = "bbox")
private Geometry bbox;
1
  • it returns @OneToOne or @ManyToOne on com.interpark.lab.tour.geolocation.model.ExpediaRegionUnion.polygon references an unknown entity: org.locationtech.jts.geom.Geometry
    – horoyoi o
    Commented Feb 4, 2020 at 5:17
9

Regarding the answer from @molholm, I would advise against using a deprecated dependency. The specific problem is that earlier versions of Hibernate did not convert java.time.* by them self, so you had to write a converter. The latest version (5.2.1.Final from 06/2016) seems to have an integrated converter. But I would still advise you to write your own and add it to your attribute. I.e.:

@Convert(converter = LocalDateConverter.class)
private LocalDate timestamp;

And here is the converter:

import java.sql.Date;
import java.time.LocalDate;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter
public class LocalDateConverter implements AttributeConverter<LocalDate, Date> {

    @Override
    public Date convertToDatabaseColumn(LocalDate entityValue) {
        if (entityValue == null) {
            return null;
        }
        return Date.valueOf(entityValue);
    }

    @Override
    public LocalDate convertToEntityAttribute(Date databaseValue) {
        if (databaseValue == null) {
            return null;
        }
        return databaseValue.toLocalDate();
    }
}
0
9

I was facing this on a @NamedNativeQuery + @SqlResultSetMapping scenario. The @ConstructorResult's targetClass had a Custom Enum inside. Changing it to String and later converting it in my code resolved the issue.

1
  • I faced this same problem and solved it the same. Enums work fine in other scenarios and it even successfully matches the arguments of the constructor with the Mapping in ConstructorResultColumnProcessor#resolveConstructor(). Not following how a simple enum by String does not work with valueOf()
    – jediwompa
    Commented Feb 19, 2021 at 17:51
3

Your entity mapping annotations (or xml) do not match your db table. So hydration/deserialization failed.

So which column is the problem? It does not tell you directly.

One clue is the hex codes at the end eg invalid stream header: 53....

53 happens to be the ascii code for "S". (https://ascii.cl/)

You can get the hex like this: select hex(MyColumn) from MyTable;

So you can look at the hex of suspicious columns until you find it.

Also, you can remove the columns one-by-one from the entity-mapping (eg comment out @Column and replace it with @Transient) until it works. Start with the suspicious ones eg enums or custom serializers. Or perhaps with any columns you just added that might have made it break.

2

Please make sure your entity objects are implementing the Serializable interface. Please select the option to make your objects Serializable in whatever tool you are using.

Some thing like this

public class Way implements Serializable {
    private static final long serialVersionUID = 1L;
0
2

I faced this issue :

HTTP Status 500 - Request processing failed; nested exception is org.hibernate.type.SerializationException: could not deserialize

Got solution also.

For me db side some rows manually entered the data after trying to retrieve the data raised exception deleted the manually entered rows after that tried to retrieve the data so this time no exception. Means if you insert the data serialized entities through hibernate in db store it. Db stores serialized objects format and retrieve db rows through serialized entities.

2

The answer from Alexey Simonov almost works for me. However, I am still forced to used Java 7 and I am using the java.time backport from ThreeTen.

In my case, I have just used a different converter suited for the backported classes:

@Column(name = "lastupdate", nullable = false)
@Convert(converter = ThreeTenBackPortJpaConverters.LocalDateConverter.class)
private LocalDate lastUpdate;
1

This type of issue related to hibernate-spatial dependency to the project or related to hibernate dialect in the case of geometry (in Spring Boot it is spring.jpa.database-platform property)? It should help.

1

I had a similar problem with the exception, but the cause was slightly different for me. In the POJO generation, an Oracle data type "TIMESTAMP (6) WITH TIME ZONE" became an object of type Serializable. Since this attribute was not relevant for me, I just removed it.

1

I just took 30 of my minutes on this similar problem Caused by: java.io.StreamCorruptedException: invalid stream header: 30313033. This solution posted in hibernate-spatial Nibble helped me http://hibernate-spatial.1140993.n2.nabble.com/exception-disabling-contexual-lob-creation-tp7572477p7572484.html.

Male sure you set spring.jpa.database-platform=org.hibernate.spatial.dialect.postgis.PostgisDialect In place of ##spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

Usually if this is the culprit you'll find out in the Hibernate logs INFO Level

Look for HHH000400: It should be Using dialect: org.hibernate.spatial.dialect.postgis.PostgisDialect for correct setting.

0

For others with the same problem where none of the previous answers helped to solve the issue:

TLDR: Check your dependencies / referenced libraries for duplicates.

The mentioned error message can also show up when a project already has some older (or same) version of the vividsolutions/locationtech JTS library included, and then later on hibernate-spatial was added to the project (which ships with its own JTS library dependency). This can be especially hard to figure out, when hibernate-spatial resides in a different (for example osgi) module and thus no compiler warnings show the different library versions being used in different parts of your code.

The Sample code of the thread starter references object type "Geometry", thus the JTS (or geolatte) library was very likely used, which also means that hibernate-spatial was most likely used.

0

This error can happen due to many reasons or possible scenarios, the best way to isolate is to enable the hibernate LOG level to INFO to source where its originating from.

I encountered this error recently and its because we have custom JSON to String convertor, which is not being applied to an JPA entity property.

0

Just another outlier if you end up stuck with this one. In my case the IDE can kindly auto-imported java.security.Timestamp instead of java.sql.Timestamp - the latter being serializable.

The backtrace as per the OP and error below were being seen. Ho hum.

StreamCorruptedException: invalid stream header: 78690512 
0

Brother, this error already happened to me, that happen 'cause the variable types doesn't match with the DB columns data types.

Sample: Your MySQL schema has a row 'age' with (INT) type.

Your code has his identifier 'age' with a (Number) type, it must be (Integer) type to solve the 'Serialization error).

Hoppe you can solve this problem, people :D

1
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Oct 24, 2021 at 2:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.