object references an unsaved transient instance - save the transient instance before flushing:

来源:互联网 发布:夜神模拟器mac版问题 编辑:程序博客网 时间:2024/05/22 05:14


 

object references an unsaved transient instance - save the transient instance before flushing:

 

译意:对象引用了一个未被保存的瞬态实例,保存对象前先保存这个瞬态实例。

 

Hibernate 保存对象时会先判断该对象是否引用其它对象,如果引用了其它对象,则判断其它对象是否存在,如果其它对象不存在,则报上述异常。

 

例子:

车:

publicclass Car {

 

   private String no;   //车子的唯一性标识

   private String color;

    

   public String getNo() {

      returnno;

   }

   publicvoid setNo(String no) {

      this.no = no;

   }

   public String getColor() {

      returncolor;

   }

   publicvoid setColor(String color) {

      this.color = color;

   }

}

人:

publicclass Person {

    

   private String idCard;   //人的唯一性标识

   private String name;

   privateintage;

   private Car car;

    

   public String getIdCard() {

      returnidCard;

   }

   publicvoid setIdCard(String idCard) {

      this.idCard = idCard;

   }

   public String getName() {

      returnname;

   }

   publicvoid setName(String name) {

      this.name = name;

   }

   publicint getAge() {

      returnage;

   }

   publicvoid setAge(int age) {

      this.age = age;

   }

   public Car getCar() {

      returncar;

   }

   publicvoid setCar(Car car) {

      this.car = car;

   }

}

 

测试:

publicclass Test {

 

   publicstaticvoid main(String[] args) {

      Car car =new Car();

      car.setNo("lu hu");

      car.setColor("white");

      Person person =new Person();

      person.setIdCard("11111111111");

      person.setCar(car);

      person.setName("zsc");

      person.setAge(100);

      save(person);   //调用hibernate的保存对象方法

   }

}

 

说明:当使用hibernate保存person对象时会先检查car对象是否存在,如果car对象不存在刚会报上述异常。人对象引用了车子对象,当保存人对象时必须保证人对象引用的车子对象存在才能保存,否则抛异常。

 

0 0
原创粉丝点击