简体   繁体   中英

MyBatis Mapper association reflected in java class

I wonder do one have to reflect the associated property in the class

If I use select with a join and then create a mapper as ie

<resultMap type="Company.Company" id="companyResult"  >
    <result column="id"    property="id" />
    <result column="name"  property="name" />    
    <association property="CompanyLevelId" resultMap="LevelMap" />
</resultMap>

<resultMap id="LevelMap"   type="Company.CompanyLevel"  >
    <id     column="CompanyLevelId"    property="CompanyLevelId" />
    <result column="Operator"         property="Operator" />
    <result column="Level"            property="level" />
</resultMap>

What would my Company class look like? Do I have to create aa new class that includes the class Company level as an object?

The Company class will have three fields, an integer id, a String name, and a CompanyLevel object called, in this case, CompanyLevelId. The CompanyLevel class will also have three fields, CompanyLevelId, Operator, and level.

The association will convert the result of your join into a CompanyLevel object as defined by the LevelMap result map.

So your java class for Company should look like:

public class Company{
    int id;
    String name;
    CompanyLevel CompanyLevelId; //this name is defined by the 'property' attribute

    public Company(){
    }
    //getters and setters
}

And CompanyLevel will look like:

public class CompanyLevel{
    int CompanyLevelId;  //once again defined by 'property' attribute
    String Operator;
    int level;

    public CompanyLevel(){
    }
    //getters and setters
}

To make it clearer I would change the property name from CompanyLevelId to something like level for the Company class and id for the CompanyLevel class and specify a java type for the association. That will make it look like this:

<resultMap type="Company.Company" id="companyResult"  >          
    <result column="id"    property="id" />          
    <result column="name"  property="name" />              
    <association property="level" resultMap="LevelMap" javaType="Company.Company" />          
</resultMap>          

<resultMap id="LevelMap"   type="Company.CompanyLevel"  >          
    <id     column="CompanyLevelId"    property="id" />          
    <result column="Operator"         property="operator" />          
    <result column="Level"            property="level" />          
</resultMap> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM