[JAVAEE Learning Notes] hibernate03: Detailed multi-table operations, cascading, relationship maintenance and exercises: adding contacts

One-to-many | many-to-one

1. Relational expression

Expressions in the Expressions

  

Entity expression

  

Expressions in orm metadata

One-to-many

        <! - Sets, one-to-many relationships, configure in configuration files - >
        <!-- 
            Name attribute: collection attribute name
            Column attribute: foreign key column name
            Class attribute: the full class name of the object associated with me
         -->
        <set name="linkMens" inverse="true" cascade="delete"  >
            <key column="lkm_cust_id" ></key>
            <one-to-many class="LinkMan" />
        </set>

More to one

        <! - Many to one-->
        <!-- 
            Name attribute: reference attribute name
            Column attribute: foreign key column name
            Class attribute: the full class name of the object associated with me
         -->
        <many-to-one name="customer" column="lkm_cust_id" class="Customer"  >
        </many-to-one>

2. Operation

Operational association properties

        //3 operation
        Customer c = new Customer();
        c.setCust_name("Wisdom Podcast");
        
        LinkMan lm1 = new LinkMan();
        lm1.setLkm_name("Dawn of Dawn");
        
        LinkMan lm2 = new LinkMan();
        lm2.setLkm_name("Liu Yuedong");
        
        //Express one-to-many,There are multiple contacts under the customer
        c.getLinkMens().add(lm1);
        c.getLinkMens().add(lm2);
        
        //Express pairs,Which customer does the contact belong to?
        lm1.setCustomer(c);
        lm2.setCustomer(c);
        
        
        session.save(c);
        session.save(lm1);
        session.save(lm2);

3. Advanced operation

Cascade operation

         <!-- 
             Cascade operation: cascade
                 save-update: Cascading save updates
                 delete: Cascade deletion
                 all:save-update+delete
             Cascade operation: Simplify operation. The purpose is to save two lines of code.
          -->
        <set name="linkMens" inverse="true" cascade="delete"  >
            <key column="lkm_cust_id" ></key>
            <one-to-many class="LinkMan" />
        </set>

Conclusion: Simplify the operation. Be sure to use save-update. It is not recommended to use delete.

 

Relation Maintenance

  

When saved, both sides will maintain the foreign key relationship. Relations are maintained twice, which is redundant. Redundant maintenance relations statements are obviously maintained by the client side.

          The inverse attribute: Is the configuration relationship maintained? 
                  true: customer does not maintain relationships
                  False (default): customer maintains relationships
                  
              inverse attribute: Performance optimization. Improve the performance of relationship maintenance.
              Principle: No matter how you give up, there will always be one party who must maintain the relationship.
              In a one-to-many relationship, one party gives up and only one party gives up.
          -->
        <set name="linkMens" inverse="true" cascade="delete"  >
            <key column="lkm_cust_id" ></key>
            <one-to-many class="LinkMan" />
        </set>

 

2. Many-to-many

1. Relational expression

Expressions in the Expressions

  

 

Object

  

orm metadata

        <! - Mu lt i-to-Many Relation Expressions - >
        <!-- 
            Name: Collection property name
            Table: Configure the middle table name
            key
             |- column: Foreign key, someone refers to the foreign key column name of "I"
             Class: Which class do I have a many-to-many relationship with?
             Column: Foreign key. I refer to the foreign key column name of Biren.
         -->
         <! - Cascade cascade operation:
                     save-update: Cascading save updates
                     delete: Cascade deletion
                     all: Cascade save update + Cascade delete
             Conclusion: cascade simplifies code writing. This attribute makes it indifferent not to use it. It is recommended that only save-update be used.
                  If delete operation is too dangerous, especially in many-to-many. It is not recommended.
                      -->
        <set name="roles" table="sys_user_role" cascade="save-update" >
            <key column="user_id" ></key>
            <many-to-many class="Role" column="role_id" ></many-to-many>
        </set>

 

2. Operation

Operational association properties

        //3> User Expressive Relations
        u1.getRoles().add(r1);
        u1.getRoles().add(r2);
        
        u2.getRoles().add(r1);
        u2.getRoles().add(r2);
        
        //4> Role Expressive Relations
        r1.getUsers().add(u1);
        r1.getUsers().add(u2);
        
        r2.getUsers().add(u1);
        r2.getUsers().add(u2);
        
        //5> call Save Method One-time Preservation
        session.save(u1);
        session.save(u2);
        session.save(r1);
        session.save(r2);

 

3. Operation Advancement

inverse attribute

    <! -- Use the inverse attribute
            true: Abandoning Maintaining Foreign Key Relations
            False (default): Maintaining relationships
            
        Conclusion: In the future, if we encounter many-to-many relationship, we must choose one side to abandon the maintenance relationship.
             Generally, who gives up depends on the direction of the business. For example, when entering an employee, it is necessary to assign the role to which the employee belongs.
             Then the business direction is to maintain roles by employees. Roles do not need to maintain relationships with employees. Roles abandon maintenance.
         -->        
        <set name="users" table="sys_user_role" inverse="true" >
            <key column="role_id" ></key>
            <many-to-many class="User" column="user_id" ></many-to-many>
        </set>

Cascading attributes

  

         <! - Cascade cascade operation:
                     save-update: Cascading save updates
                     delete: Cascade deletion
                     all: Cascade save update + Cascade delete
             Conclusion: cascade simplifies code writing. This attribute makes it indifferent not to use it. It is recommended that only save-update be used.
                  If delete operation is too dangerous, especially in many-to-many. It is not recommended.
                      -->
        <set name="roles" table="sys_user_role" cascade="save-update" >
            <key column="user_id" ></key>
            <many-to-many class="Role" column="role_id" ></many-to-many>
        </set>

 

3. Exercise: Adding Contacts

  servlet:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1> Obtain parameters and package them LinkMan Object
        LinkMan lm = new LinkMan();
        try {
            BeanUtils.populate(lm, request.getParameterMap());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //2> call Service Preservation LinkMan object
        lms .save(lm);
        //3> Redirect to LinkMan List of(404)
        response.sendRedirect(request.getContextPath()+"/ListLinkManServlet");
    }

 

  service:

    private CustomerDao cd =new CustomerDaoImpl();
    private LinkManDao lmd = new LinkManDaoImpl();
    public void save(LinkMan lm) {
        //Open a transaction
        HibernateUtils.getCurrentSession().beginTransaction();
        
        try {
            //1 According to customers id Get the customer object
            Long cust_id = lm.getCust_id();
            Customer c = cd.getById(cust_id);
            //2 Put customers in LinkMan Intermediate Expressive Relations
            lm.setCustomer(c);
            //3 Preservation LinkMan
            lmd.save(lm);
        } catch (Exception e) {
            e.printStackTrace();
            //Roll back transactions
            HibernateUtils.getCurrentSession().getTransaction().rollback();
        }
        //Submission transaction
        HibernateUtils.getCurrentSession().getTransaction().commit();
        
    }

  dao:

    public void save(LinkMan lm) {
        //1 Get session
        Session session = HibernateUtils.getCurrentSession();
        session.save(lm);
    }

Keywords: Java Attribute Session

Added by abo28 on Tue, 25 Jun 2019 03:27:10 +0300