Hibernate:无法反序列化 - 无效的流标头

时间:2014-04-13 22:59:30

标签: java spring hibernate jpa

有关如何解决此错误的任何想法?我正在使用Spring JPA和Hibernate。以下必要的详细信息。

实体类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
@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

}

和堆栈跟踪:

堆栈跟踪非常庞大。我将整个堆栈跟踪粘贴到下面以供参考和快速TL; DR在这里:

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

完整的堆栈跟踪如下:

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

更新

我将Ways实体类更新为以下内容,但仍然出现错误:

@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;

16 个答案:

答案 0 :(得分:59)

对于有相同错误的其他人(不回答这个问题)

由于 <fragment android:id="@+id/maps_fragment" android:name="com.google.android.gms.maps.MapFragment" android:layout_width="match_parent" android:layout_height="match_parent" /> 类型的字段,我遇到了hibernate 4.3和5.0.5的这个错误,我有几个使用LocalDateTime的实体,但只有其中一个导致了这个问题,我不知道为什么。

通过添加以下依赖项来修复它:

java.time.LocalDateTime

答案 1 :(得分:26)

当某些事情无法反序列化时,就会发生这个问题(谢谢你,Captain Obvious)。在您的实体映射中,以下内容看起来很可疑:

@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;

我的建议是要查看GeometryObject2ObjectHashMap类 - 检查它们是否可序列化所有字段都可序列化,或标记为{ {1}}关键字。此外,如果您在这里发布这些课程,这也可能有所帮助。 transient班级列表也可能有所帮助。

答案 2 :(得分:9)

关于kaba713 answer并通过Hibernate转换java.time.*

我使用org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters;,它适用于Spring-Boot 1.5.4。

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

我们不需要编写自定义转换器。

答案 3 :(得分:7)

问题应该是几何关系,它被映射为常规列,因此Hibernate尝试将一个简单的列映射到Geometry对象。我有一个类似的问题,解决方案是明确定义关系,如:

@OneToOne
@JoinColumn(name = "bbox")
private Geometry bbox;

答案 4 :(得分:7)

关于来自@molholm的answer,我建议不要使用已弃用的依赖项。具体问题是早期版本的Hibernate没有自己转换java.time.*,所以你必须编写一个转换器。最新版本(从2016年6月起的5.2.1.Final)似乎有一个集成的转换器。但我仍然建议你自己编写并将其添加到属性中。即:

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

这是转换器:

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();
    }
}

答案 5 :(得分:2)

请确保您的实体对象正在实现Serializable接口。请选择使用您正在使用的任何工具使您的对象可序列化的选项。

有点像这样

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

答案 6 :(得分:2)

我在@NamedNativeQuery + @SqlResultSetMapping方案中面对此问题。 @ ConstructorResult的targetClass里面有一个Custom Enum。将其更改为String并稍后在我的代码中转换它解决了这个问题。

答案 7 :(得分:2)

Alexey Simonov的回答几乎对我有用。但是,我仍然被迫使用Java 7,并且仍在使用ThreeTen中的 java.time 反向端口。

就我而言,我只是使用了一个适合于向后移植的类的转换器:

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

答案 8 :(得分:1)

我遇到了这个问题:

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

也有解决方案。

对于我的数据库侧面一些行手动输入数据后,尝试检索数据引发的异常删除了手动输入的行后,试图检索数据所以此时没有异常。 表示如果在数据库存储中通过hibernate插入数据序列化实体。  Db存储序列化对象格式并通过序列化实体检索数据库行。

答案 9 :(得分:0)

您的实体映射注释(或xml)与您的数据库表不匹配。因此水合/反序列化失败。

那么问题出在哪一列?它不会直接告诉您。

一个提示是末尾的十六进制代码 例如无效的流头:53 ....

53恰好是“ S”的ASCII码。 (https://ascii.cl/

您可以像这样获得十六进制:sudo R CMD javareconf

因此,您可以查看可疑列的十六进制,直到找到它为止。

此外,您可以从实体映射中一一删除列(例如,注释掉@Column并将其替换为@Transient),直到它起作用为止。从可疑的对象开始,例如枚举或自定义序列化程序。或者,也许您刚刚添加的任何列都可能使其崩溃。

答案 10 :(得分:0)

这种类型的问题与项目的休眠空间依赖性有关,还是在几何情况下与休眠方言有关(在Spring Boot中,它是spring.jpa.database-platform属性)?应该会有帮助。

答案 11 :(得分:0)

我也有类似的问题,但原因对我来说略有不同。在POJO生成中,Oracle数据类型“ TIMESTAMP(6)WITH TIME ZONE”成为类型Serializable的对象。由于此属性与我无关,因此我将其删除。

答案 12 :(得分:0)

对于具有相同问题的其他人,以前的答案都无法帮助解决该问题:

TLDR :检查您的依赖项/引用的库是否重复。

当项目已经包含某个更旧(或相同)版本的vidivesolutions / locationtech JTS库,然后在以后将hibernate-spatial添加到项目中时,也会显示该错误消息(该版本附带了它自己的) JTS库依赖项)。当休眠空间驻留在不同的模块(例如osgi)中并且因此没有编译器警告显示代码的不同部分使用的库版本不同时,这一点尤其难以弄清。

线程启动器的示例代码引用对象类型“ Geometry”,因此很可能使用了JTS(或geolatte)库,这也意味着最有可能使用了休眠空间。

答案 13 :(得分:0)

我只花了30分钟的时间解决这个类似的问题原因:java.io.StreamCorruptedException:无效的流标头:30313033 。休眠空间Nibble中发布的此解决方案对我http://hibernate-spatial.1140993.n2.nabble.com/exception-disabling-contexual-lob-creation-tp7572477p7572484.html有帮助。

男性确定您已设置 spring.jpa.database-platform=org.hibernate.spatial.dialect.postgis.PostgisDialect 代替 ##spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

通常,这是您在休眠日志 INFO级别

中发现的罪魁祸首

寻找 HHH000400 : 正确设置应为Using dialect: org.hibernate.spatial.dialect.postgis.PostgisDialect

答案 14 :(得分:0)

由于许多原因或可能的情况,可能会发生此错误,隔离的最佳方法是启用休眠LOG级别的INFO以使其来源。

我最近遇到此错误,是因为我们有自定义的JSON到String转换器,该转换器未应用于JPA实体属性。

答案 15 :(得分:0)

如果最后被这个难题困扰,那就另当别论了。就我而言,IDE可以自动导入java.security.Timestamp而不是java.sql.Timestamp-后者可以序列化。

正在查看根据OP的回溯和以下错误。哼!

StreamCorruptedException: invalid stream header: 78690512