开发者

Hibernate and Child Objects (add versus clear)

Lets say I have domain model with Automobile and Wheels. Wheels is a List of Wheels Wheels has a many-to-one relationship to Automobile.

If I get an object back from Hibernate and it has 4 wheels. I take that object remove the 4 wheels and add 4. And then Save.

If I ask Hibernate for the object again and it returns an auto with 8 wheels... what are we doing wrong? I don't have access to the source for a few days but want to give our Java devs a push in the right direction. Thanks.开发者_JS百科


I believe, but am not 100% positive, that this depends on the cascade property of the collection. For example, if you have:

<hibernate-mapping package="com.foo">
  <class name="Automobile">
  ...
    <set name="Wheels" cascade="delete-orphan"> <!-- or "all-delete-orphan" -->
      ...
    </set>
  </class>
</hibernate-mapping>

Then that would probably do it.


Your question sounds like a collection of @Embeddable class where a component (The part - Wheel) has its lifecycle bound to that of its owning entity instance (Automobile)

@Entity
public class Automobile {

    private Integer id;

    private Set<Wheels> wheelsSet = new HashSet<Wheels>();

    @Id
    @GeneratedValue
    public Integer getId() {
        return this.id;
    }

    @CollectionsOfElements
    @JoinTable("AUTO_WHEELS")
    public Set<Wheels> getWheelSet() {
        return this.wheelsSet;
    }

}

If you do

Automobile auto = session
                  .createQuery("from Automobile a left join fetch a.wheelSet where a.id = :id")
                  .setParameter("id", id)
                  .list().get(0);

And

/**
  * All of wheels removed
  */       
auto.getWheelSet().clear();

/**
  * New Wheels added
  */  
auto.getWheelSet().add(new Wheel());
auto.getWheelSet().add(new Wheel());
auto.getWheelSet().add(new Wheel());
auto.getWheelSet().add(new Wheel());

session.update(auto);

It will fullfil your needs. But keep in mind you must provide equals and hashCode implementation To work fine

@Embeddable
public class Wheel implements Serializable {

    /**
      * equals and hashCode goes here
      * Prefer To use business key
      */

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜