0

I am farily new to Hibernate and here i am stuck with a transientexception. Please help.

Exception occured while saving the object Location object references an unsaved--transient instance - save the transient instance before flushing: <City object>; nested exception is org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

I am getting above exeption when i am trying to save data into my location table which has a City object with all its elements referring to null.

Location object       
   private String LocationAddress;  
   @ManyToOne
   @JoinColumn(name = "CITYID")
   private City city;


City
   private String cityName;
   private int cityId;

In Location table CityID is nullable field because city is not a required field. And we have a city table which is a static table so we dont want to insert data in City table. Now when we are storing Location object. It stores data fine if City object has some values like some city. But throws exception when object contains a blank object(cityName and cityId are null)

Please help.

Example scenario

Successful
      Location 
       locationAddress = "test Address"
        city 
           cityId="1"
           cityName="testCity"

Failure
      Location 
           locationAddress = "test Address"
           city 
               cityId=null
               cityName=null
4

2 回答 2

0

如果您尝试保存一个Location实际引用no City的实例,那么您应该Location.City引用null,而不是创建City字段为 的实例null

( Hibernate 认为City哪些字段的实例null就像您想要在cities表中的哪些列值的新记录一样null- 这没有多大意义)

于 2013-01-24T23:06:47.537 回答
0

如果没有看到您的代码,很难确定,但听起来您在保存课程City之前没有保存您的代码Location。您有两个持久化选项:

您可以使用@Cascade注释将插入从父级级联到子级。这样做,你可以坚持这个Location类,而 Hibernate 会处理剩下的事情。

@ManyToOne
@JoinColumn(name = "CITYID")
@Cascade(CascadeType.PERSIST)  //Or ALL if you want Updates, Deletes to go to
private City city;

更多关于@Cascade 这里

如果您不想这样做,则需要City在保存Location.

于 2013-01-24T22:52:28.937 回答