外键字段为空时抛出TransientObjectException解决方法

类A和类B分别对应数据库两个表T_A,  T_B,A为父表,B子表。

public class A{

private String aid,

private B tB,

}

public class B{

private String bid,

}

向数据库添加一个A的实例时,如果tB.getBid()为空,抛出:

org.hibernate.TransientObjectException: object references an unsaved transient instance

– save the transient instance before flushing

解决:

根据form表单构造A的实例a1时,判断是否存在B的信息,当不存在时,不要在a1中构造B的实例。

例:

if(bina exist){

B b1 = new B();

b1.setBid(bid);

a1.setB(b1);

}else {

a1.setB(null);

}

This entry was posted in Computer, Java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s