Mybatis (six)--cascading delete

Description of Requirement

      Today's requirement is to delete the role data bound to the resource at the same time when deleting a resource. There are two tables, the resource table and the role and resource binding table. There are two methods for cascading deletion: 1. Directly establish constraints when creating a table, When the parent table deletes data, the database will automatically delete the data in the child table. ② The cascade deletion is implemented through code, first delete the child table data, and then delete the data in the parent table.

Implemented through database

     You can refer to the blog post: http://www.jb51.net/article/88148.htm

     In this way, if we want to delete the data of the parent table, the data of the child table will be deleted, and our business requirement is whether the deletion in the table is identified by the is_delete field, so this method can realize the deletion of cascading tables, But it does not meet our needs, and only one such idea is provided here.

Implemented through code

    First write an interface to delete resource and role bindings:

/**
     * Delete related role resource binding data based on resource id
     * @param applicationIds resource ids
     * @return number of affected lines
     */
    int deleteByApplicationId(List<String> applicationIds);
<delete id="deleteByApplicationId">
        UPDATE tc_role_application
        SET is_delete =1
        WHERE application_id IN (
        <foreach collection="list" item="id" separator=",">
            #{id}
        </foreach>
        ) AND is_delete = 0

    </delete>

   Write an interface to delete resources:   

int deleteByIds(@Param("list") List<String> var1, @Param("operator") String var2);
<delete id="deleteByIds">
    update tc_application set is_delete = 1  , update_time=now() , operator = #{operator,jdbcType=VARCHAR}
    where id in (
        <foreach collection="list" item="id" separator=",">
            #{id}
        </foreach>
        )  and is_delete = 0
  </delete>      

When performing delete, delete the child table data first, and then delete the parent table data:

/**
     * Batch delete resources and delete related resource role binding data under it
     * @param ids resource ids
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteApplicationByIds(List<String> ids) {
        String user = TenancyContext.UserID.get();
        //First delete the resource and role binding data in the resource role table
        roleApplicationService.deleteByApplicationId(ids);
        // delete resource table data
        this.deleteByIds(ids, user);
    }

Summarize

     Choose the method that suits you according to your needs and actual situation.

     

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325936394&siteId=291194637