使用Hibernate序列化POJO列表 [英] Serializing List of POJOs using Hibernate

查看:76
本文介绍了使用Hibernate序列化POJO列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用JPA映射到数据库表的Java类。在这个类的内部,我有一个 List< Code> ,我需要将它们存储在数据库中。

c $ c> Code 类未映射到Hibernate中。有没有一种方法来序列化 List< Code> ,而不将映射到Hibernate的Code类?



错误讯息:

  org.hibernate。 exception.SQLGrammarException:无法插入集合[com.app.Account.codes#2] 

问题是当Hibernate尝试序列化我的列表时,我发现错误。

  @Entity 
@Table(name =帐户,目录=database1)
公共类帐户{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name =id)
private String id

@Column(name =type)
private String type;

@CollectionOfElements
@Column(name =codes)
List< Code>码;
...
...
}


public class Code implements Serializable {
//这是一个基本的POJO,它是没有映射到Hibernate中。我只想将这个对象
//存储在数据库中。


解决方案

您需要注释代码字段与 @Lob ,而不是 @CollectionOfElements



请参阅 http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#d0e6099 和以下段落。



然而,这是持久化对象列表的一种非常脆弱的方式,因为它使用了二进制序列化,如果列表或代码类发生更改,该序列化可能会很快变为非向后兼容。使用数据库工具查询或检查也是不可能的。



我宁愿将Code类映射为实体或嵌入。


I have a Java class that is mapped to a database table using JPA. Inside this class I have a List<Code> that I need to store in database.

So the Code class is not mapped into Hibernate. Is there a way to Serialize the List<Code> without mapping the Code class into Hibernate? Thanks in advance.

Error Message:

org.hibernate.exception.SQLGrammarException: could not insert collection [com.app.Account.codes#2]

Problem is that I'm getting error when Hibernate attempts to Serialize my List.

@Entity
@Table (name="account", catalog="database1")
public class Account{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column (name = "id")
    private String id

    @Column (name = "type")
    private String type;

    @CollectionOfElements
    @Column (name = "codes")
    List<Code> codes;
    ...
    ...
}


public class Code implements Serializable{
//This is a basic POJO that is not mapped into Hibernate. I just want this object
//to be stored in database.
}

解决方案

You need to annotate the codes field with @Lob, not with @CollectionOfElements.

See http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#d0e6099 and the following paragraph.

This is a very fragile way of persisting a list of objects, though, because it uses binary serialization, which might quickly become non-backward compatible if the list or the Code class changes. It's also impossible to query or inspect using database tools.

I would rather map the Code class as an entity or as an embeddable.

这篇关于使用Hibernate序列化POJO列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆