为什么复合 ID 类必须实现可序列化?

2022-08-31 15:43:05

如果我创建一个不实现可序列化的复合id类,例如:

@Entity
@Table(name = "board")
public class Board {
    @Id
    @Column(name = "keyword_news_id")
    private int id;

    @Id
    @Column(name = "board_no")
    private int boardNo;
....

错误发生如下:

Caused by: org.hibernate.MappingException: composite-id class must implement Serializable: com.estinternet.news.domain.IssueNewsBoard
    at org.hibernate.mapping.RootClass.checkCompositeIdentifier(RootClass.java:263)
    at org.hibernate.mapping.RootClass.validate(RootClass.java:244)
    at org.hibernate.cfg.Configuration.validate(Configuration.java:1362)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1865)
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(LocalSessionFactoryBean.java:860)
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:779)
    at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)

休眠实体类不需要是可序列化的。那么,为什么复合 ID 类必须实现可序列化?我读了这个帖子,但它没有给我足够的信息。


答案 1

会话对象需要可序列化,因此它引用的所有对象也必须可序列化。该 ID 用作索引会话中加载的对象的键。在CompositeId s的情况下,类本身被用作id。


答案 2

推荐