我有一个持久类:
public class NotifEventGroupRel implements Serializable{
private static final long serialVersionUID = 7616645672995663305L;
private Long eventGroupId;
private String eventName;
private NotifEventGroup notifEventGroup; //// composite id property
private EmailTmplt emailTmplt; // composite id property
private SmsTmplt smsTmplt; // composite id property
....
}
它的 hbm.xml 文件是:
<hibernate-mapping>
<class name="NotifEventGroupRel" table="TBLMEVENTGROUPREL">
<composite-id>
<key-many-to-one name="notifEventGroup" class="NotifEventGroup" lazy="false" >
<column name="EVENTGROUPID" precision="20" scale="0" not-null="true" />
</key-many-to-one>
<key-property name="eventName" type="java.lang.String">
<column name="EVENT" />
</key-property>
</composite-id>
<many-to-one name="emailTmplt" class="EmailTmplt" lazy="false" not-null="false" >
<column name="EMAILTMPLTID"></column>
</many-to-one>
<many-to-one name="smsTmplt" class="SmsTmplt" lazy="false" not-null="false">
<column name="SMSTMPLTID" />
</many-to-one>
</class>
</hibernate-mapping>
形成复合 id 的属性类是:
public class NotifEventGroup {
private Long eventGroupId;
private String name;
.......
}
public class EmailTmplt {
private Long emailTmpltId;
private String name;
.....
}
public class SmsTmplt {
private Long smsTmpltId;
private String name;
..........
}
- 我是否需要将以下属性设置为 transient :
(如下所示)
private transient NotifEventGroup notifEventGroup; //// composite id property
private transient EmailTmplt emailTmplt; // composite id property
private transient SmsTmplt smsTmplt; // composite id property
因为 findbug 为我提供了可序列化类中的非 transient 不可序列化实例字段
字段错误(如果非 transient )。
- 或者我必须使其相应的类可序列化吗?
执行上述两种情况会产生什么影响?
最佳答案
报告该错误是因为实现Serialized
的类中的所有字段也必须是Serialized
。
使字段变为 transient
使字段 transient
意味着它们应该在序列化中被忽略,我认为你不希望这样(因为它们包含在 hibernate 映射文件中)。
来自 Java 语言规范,Java SE 7 Edition, Section 8.3.1.3. transient 字段:
Variables may be marked transient to indicate that they are not part of the persistent state of an object.
使类实现可序列化
类NotifEventGroup
、EmailTmplt
和SmsTmplt
也应该实现Serialized
接口(interface)。实现Serialized
实际上什么都不做,它只是一个标记接口(interface),用于通知用户该类可以被序列化。
关于java - 形成复合键的持久类属性是否也需要可序列化或在不可序列化的情况下是 transient 的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19044862/