Using inverse true in hibernate

后端 未结 2 1716
忘了有多久
忘了有多久 2021-01-02 05:16

I am going through the hibernate documentation and came across the concept of inverse attribute. I am new to Hibernate so I am feeling difficulty in understanding the concep

相关标签:
2条回答
  • 2021-01-02 05:53

    inverse="true" basically means that the inverse relationship is also mapped within the class definition of the other class. But, it's real meaning is that it defines which side is the parent or the relationship owner for the two entities (parent or child). Hence, inverse="true" in a Hibernate mapping shows that this class (the one with this XML definition) is the relationship owner; while the other class is the child.

    If you want to know more about this, then I would definitely have a look at this article: http://www.mkyong.com/hibernate/inverse-true-example-and-explanation/ because it's easy to be misled of the meaning of this attribute in hibernate.

    0 讨论(0)
  • 2021-01-02 05:54

    Inverse keyword is created to defines which side is the owner to maintain the relationship. The procedure for updating and inserting varies according to this attribute.

    Let's suppose we have two tables:

    principal_table, middle_table

    with a relationship of one to many. The hiberntate mapping classes are Principal and Middle respectively.

    So the Principal class has a SET of Middle objects. The xml mapping file should be like following:

    <hibernate-mapping>
        <class name="path.to.class.Principal" table="principal_table" ...>
        ...
        <set name="middleObjects" table="middle_table" inverse="true" fetch="select">
            <key>
                <column name="PRINCIPAL_ID" not-null="true" />
            </key>
            <one-to-many class="path.to.class.Middel" />
        </set>
        ...
    

    As inverse is set to ”true”, it means “Middle” class is the relationship owner, so Principal class will NOT UPDATE the relationship.

    So the procedure for updating could be implemented like this:

    session.beginTransaction();
    
    Principal principal = new Principal();
    principal.setSomething("1");
    principal.setSomethingElse("2");
    
    
    Middle middleObject = new Middle();
    middleObject.setSomething("1");
    
    middleObject.setPrincipal(principal);
    principal.getMiddleObjects().add(middleObject);
    
    session.saveOrUpdate(principal);
    session.saveOrUpdate(middleObject); // NOTICE: you will need to save it manually
    
    session.getTransaction().commit();
    

    Further information can be found Here It is a well explained tutorial about how to use inverse attribute. It also shows how hinernate translate this into SQL queries.

    0 讨论(0)
提交回复
热议问题