`

mybatis 自身关联 映射

 
阅读更多

使用mybatis的时候遇到关联问题。

 

可以参考如下:

 

一个自关联的model

public class TreeDic  implements java.io.Serializable{
	private static final long serialVersionUID = 5454155825314635342L;
	
	//alias
	public static final String TABLE_ALIAS = "树形树形字典";
	public static final String ALIAS_ID = "编号";
	public static final String ALIAS_PARENT_ID = "父节点编号";
	public static final String ALIAS_PARENT_IDS = "所有父节点编号";
	public static final String ALIAS_TYPE = "分类";
	public static final String ALIAS_CODE = "键值";
	public static final String ALIAS_NAME = "标签";
	public static final String ALIAS_REMARKS = "描述";
	public static final String ALIAS_SORT = "排序";
	public static final String ALIAS_DEL_FLAG = "del_flag";
	public static final String ALIAS_VERSION = "version";
	
	//date formats
	
	
	private TreeDic parent;
	
	private List<TreeDic> childList = Lists.newArrayList();
	
	//可以直接使用: @Length(max=50,message="用户名长度不能大于50")显示错误消息
	//columns START
    /**
     * id       db_column: id 
     */	
	@Max(9223372036854775807L)
	private java.lang.Long id;
    /**
     * parent_id       db_column: parent_id 
     */	
	@NotNull @Max(9223372036854775807L)
	private java.lang.Long parentId;
    /**
     * parent_ids       db_column: parent_ids 
     */	
	@NotBlank @Length(max=255)
	private java.lang.String parentIds;
    /**
     * type       db_column: type 
     */	
	@Length(max=100)
	private java.lang.String type;
    /**
     * code       db_column: code 
     */	
	@Length(max=100)
	private java.lang.String code;
    /**
     * name       db_column: name 
     */	
	@Length(max=100)
	private java.lang.String name;
    /**
     * remarks       db_column: remarks 
     */	
	@Length(max=255)
	private java.lang.String remarks;
    /**
     * sort       db_column: sort 
     */	
	@Max(9999999999L)
	private java.lang.Integer sort;
    /**
     * del_flag       db_column: del_flag 
     */	
	@Length(max=1)
	private java.lang.String delFlag;
    /**
     * version       db_column: version 
     */	
	@Max(9999999999L)
	private java.lang.Integer version;
	//columns END

	public TreeDic(){
	    this.delFlag = "0";
	    this.version = 1;
	}

	public TreeDic(
		java.lang.Long id
	){
		this.id = id;
	}

	public void setId(java.lang.Long value) {
		this.id = value;
	}
	
	public java.lang.Long getId() {
		return this.id;
	}
	public void setParentId(java.lang.Long value) {
		this.parentId = value;
	}
	
	public java.lang.Long getParentId() {
		return this.parentId;
	}
	public void setParentIds(java.lang.String value) {
		this.parentIds = value;
	}
	
	public java.lang.String getParentIds() {
		return this.parentIds;
	}
	public void setType(java.lang.String value) {
		this.type = value;
	}
	
	public java.lang.String getType() {
		return this.type;
	}
	public void setCode(java.lang.String value) {
		this.code = value;
	}
	
	public java.lang.String getCode() {
		return this.code;
	}
	public void setName(java.lang.String value) {
		this.name = value;
	}
	
	public java.lang.String getName() {
		return this.name;
	}
	public void setRemarks(java.lang.String value) {
		this.remarks = value;
	}
	
	public java.lang.String getRemarks() {
		return this.remarks;
	}
	public void setSort(java.lang.Integer value) {
		this.sort = value;
	}
	
	public java.lang.Integer getSort() {
		return this.sort;
	}
	public void setDelFlag(java.lang.String value) {
		this.delFlag = value;
	}
	
	public java.lang.String getDelFlag() {
		return this.delFlag;
	}
	public void setVersion(java.lang.Integer value) {
		this.version = value;
	}
	
	public java.lang.Integer getVersion() {
		return this.version;
	}
	
	

	/**
     * @return Returns the parent.
     */
    public TreeDic getParent() {
        return parent;
    }

    /**
     * @param parent The parent to set.
     */
    public void setParent(TreeDic parent) {
        this.parent = parent;
    }

    /**
     * @return Returns the childList.
     */
    public List<TreeDic> getChildList() {
        return childList;
    }

    /**
     * @param childList The childList to set.
     */
    public void setChildList(List<TreeDic> childList) {
        this.childList = childList;
    }
    
    public static void sortList(List<TreeDic> list, List<TreeDic> sourcelist, Long parentId){
        for (int i=0; i<sourcelist.size(); i++){
            TreeDic e = sourcelist.get(i);
            if (e.getParent()!=null && e.getParent().getId()!=null
                    && e.getParent().getId().equals(parentId)){
                list.add(e);
                // 判断是否还有子节点, 有则继续获取子节点
                for (int j=0; j<sourcelist.size(); j++){
                    TreeDic childe = sourcelist.get(j);
                    if (childe.getParent()!=null && childe.getParent().getId()!=null
                            && childe.getParent().getId().equals(e.getId())){
                        sortList(list, sourcelist, e.getId());
                        break;
                    }
                }
            }
        }
    }

    public boolean isRoot(){
        return isRoot(this.id);
    }
    
    public static boolean isRoot(Long id){
        return id != null && id.equals(1L);
    }

    public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}
	
	public int hashCode() {
		return new HashCodeBuilder()
			.append(getId())
			.toHashCode();
	}
	
	public boolean equals(Object obj) {
		if(obj instanceof TreeDic == false) return false;
		if(this == obj) return true;
		TreeDic other = (TreeDic)obj;
		return new EqualsBuilder()
			.append(getId(),other.getId())
			.isEquals();
	}
}

   

 

    Mapper文件的配置很重要:

    

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">


<!-- 不使用namespace的话sql搜索定位会比较方便 -->
<mapper namespace="TreeDic">

	<resultMap id="RM.TreeDic" type="net.cciot.snail.sys.model.TreeDic">
        <result property="id" column="id"/>
        <result property="parentId" column="parent_id"/>
        <result property="parentIds" column="parent_ids"/>
        <result property="type" column="type"/>
        <result property="code" column="code"/>
        <result property="name" column="name"/>
        <result property="remarks" column="remarks"/>
        <result property="sort" column="sort"/>
        <result property="delFlag" column="del_flag"/>
        <result property="version" column="version"/>
        <!-- 查询父模块 -->  
        <association property="parent" column="parent_id" select="TreeDic.getById" />
        <!-- 查询子模块 -->  
        <collection property="childList" column="id" select="TreeDic.getChildList" />  
	</resultMap>
	
	<!-- 用于select查询公用抽取的列 -->
	<sql id="TreeDic.columns">
	    <![CDATA[
		id,parent_id,parent_ids,type,code,name,remarks,sort,del_flag,version
	    ]]>
	</sql>

	<!-- useGeneratedKeys="true" keyProperty="xxx" for sqlserver and mysql -->
	<insert id="TreeDic.insert" useGeneratedKeys="true" keyProperty="id">
    <![CDATA[
        INSERT INTO sys_tree_dic (
         id, parent_id, parent_ids, type, code, name, remarks, sort, del_flag, version
        ) VALUES (
         #{id}, #{parentId}, #{parentIds}, #{type}, #{code}, #{name}, #{remarks}, #{sort}, #{delFlag}, #{version}        
        )
    ]]>
		<!--	
			oracle: order="BEFORE" SELECT sequenceName.nextval AS ID FROM DUAL 
			DB2: order="BEFORE"" values nextval for sequenceName
		<selectKey resultType="java.lang.Long" order="BEFORE" keyProperty="userId">
			SELECT sequenceName.nextval AS ID FROM DUAL 
        </selectKey>
		-->
	</insert>
    
	<update id="TreeDic.update" >
    <![CDATA[
        UPDATE sys_tree_dic SET
	        parent_id = #{parentId} , parent_ids = #{parentIds} , type = #{type} , code = #{code} , name = #{name} , remarks = #{remarks} , sort = #{sort} , del_flag = #{delFlag} , version = version + 1 
        WHERE 
        	id = #{id}  	        
    ]]>
	</update>

    <delete id="TreeDic.delete">
    <![CDATA[
        UPDATE sys_tree_dic SET
            del_flag = '1'
        WHERE
        id = #{id} 
    ]]>
    </delete>
    
    <select id="TreeDic.getById" resultMap="RM.TreeDic">
		SELECT <include refid="TreeDic.columns" />
	    <![CDATA[
		    FROM sys_tree_dic 
	        WHERE 
		        id = #{id} 
	    ]]>
	</select>
	
	<select id="TreeDic.getChildList" resultMap="RM.TreeDic">
        SELECT <include refid="TreeDic.columns" />
        <![CDATA[
            FROM sys_tree_dic 
            WHERE 
                parent_id = #{id} 
        ]]>
    </select>
	
	
	<sql id="TreeDic.findPage.where">
		<!-- ognl访问静态方法的表达式 为@class@method(args),以下为调用rapid中的Ognl.isNotEmpty()方法,还有其它方法如isNotBlank()可以使用,具体请查看Ognl类 -->
		<where>	      				
	       <if test="@Ognl@isNotEmpty(id)">
				AND id = #{id}
			</if>
	       <if test="@Ognl@isNotEmpty(parentId)">
				AND parent_id = #{parentId}
			</if>
	       <if test="@Ognl@isNotEmpty(parentIds)">
				AND parent_ids = #{parentIds}
			</if>
	       <if test="@Ognl@isNotEmpty(type)">
				AND type = #{type}
			</if>
	       <if test="@Ognl@isNotEmpty(code)">
				AND code = #{code}
			</if>
	       <if test="@Ognl@isNotEmpty(name)">
				AND name = #{name}
			</if>
	       <if test="@Ognl@isNotEmpty(remarks)">
				AND remarks = #{remarks}
			</if>
	       <if test="@Ognl@isNotEmpty(sort)">
				AND sort = #{sort}
			</if>
	       <if test="@Ognl@isNotEmpty(delFlag)">
				AND del_flag = #{delFlag}
			</if>
	       <if test="@Ognl@isNotEmpty(version)">
				AND version = #{version}
			</if>
		</where>
	</sql>
		
    <select id="TreeDic.findPage.count" resultType="long">
        SELECT count(*) FROM sys_tree_dic 
		<include refid="TreeDic.findPage.where"/>    
    </select>
    
    <!--
    	分页查询已经使用Dialect进行分页,也可以不使用Dialect直接编写分页
    	因为分页查询将传 offset,pageSize,lastRows 三个参数,不同的数据库可以根于此三个参数属性应用不同的分页实现
    -->
    <select id="TreeDic.findPage" resultMap="RM.TreeDic">
    	SELECT <include refid="TreeDic.columns" />
	    FROM sys_tree_dic 
		<include refid="TreeDic.findPage.where"/>
		
		<if test="@Ognl@isNotEmpty(sortColumns)">
			ORDER BY ${sortColumns}
		</if>
		
		<if test="offset != null and pageSize != null" >
          <![CDATA[ limit #{offset} , #{pageSize} ]]>
        </if>
    </select>

	
</mapper>

 

    总结与此,方便下次使用

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics