Using inverse true in hibernate

后端 未结 2 1734
忘了有多久
忘了有多久 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: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:

    
        
        ...
        
            
                
            
            
        
        ...
    

    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.

提交回复
热议问题