我在@JoinColumn上看过很多问题,在我遇到以下情况之前,这个概念很清楚。
让我们考虑映射是OneToOne单向映射。我在父类中使用了以下的annatation:
情况1:-
@JoinColumn(name="test_Id",referencedColumnName="refToPrimaryKey")
和Entity类未实现Serializable接口。在这种情况下程序正在执行,没有任何异常。
案例2: -
@JoinColumn(name="test_Id",referencedColumnName="refToNonPrimaryKey")
和Entity类未实现Serializable接口。
此程序抛出异常,如:
threw exception [java.lang.ClassCastException:
com.homecare.persistance.resource.TestEntity cannot be cast to java.io.Serializable] with root cause
java.lang.ClassCastException: com.homecare.persistance.resource.TestEntity cannot be cast to java.io.Serializable at org.hibernate.type.CollectionType.getKeyOfOwner(CollectionType.java:414)
你能帮助我了解它为什么会发生的概念吗?
答案 0 :(得分:0)
您使用的是二级缓存吗?
cannot be cast to java.io.Serializable at org.hibernate.type.CollectionType.getKeyOfOwner(CollectionType.java:414)
根据hibernate doc,disassemble
返回对象的反汇编表示。这是Hibernate在二级缓存中使用的值,因此应该注意将值分解为最简单的形式;对于实体尤其如此
意味着把它们分解成它们的组成部分。
如果要检查org.hibernate.type.CollectionType包
//This solution would allow us to eliminate the owner arg to disassemble(), but
//what if the collection was null, and then later had elements added? seems unsafe
//session.getPersistenceContext().getCollectionEntry( (PersistentCollection) value ).getKey();
final Serializable key = getKeyOfOwner(owner, session);
if (key==null) {
return null;
}
else {
return getPersister(session)
.getKeyType()
.disassemble( key, session, owner );
}
因此,您需要在实体中实现Serializable接口
答案 1 :(得分:0)
Please find below code.let me know if you need any other information:
@Setter
@Getter
@Entity
@Table(name="test")
public class TestEntity imple`enter code here`ments Serializable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name="name")
private String name;
@Column(name="roll")
private int roll;
@Column(name="stream")
private String stream;
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="for_Key",referencedColumnName="roll")
private List<TestEntityChild> testEntityChildList;
}
Chile Entity class
@Getter
@Setter
@Entity
@Table(name="testchild")
public class TestEntityChild {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="Test_id")
private int testId;
@Column(name="city")
private String city;
@Column(name="state")
private String state;
}