一:MyBatis自关联查询映射文件

1.pojo类

public class Category implements Serializable{
	
	private String cid;   //分类主键
	private String cname;   //分类名
	private Category parent;  //父分类,是根据pid的自连接对象,一个二级分类只有一个一级分类
	private String desc;   //描述
	private List<Category> children;  //子分类,一个一级分类可能有多个二级分类,而二级分类无子分类
	
	//setter and getter method...
}

2.dao接口

public interface CategoryDao {
		
	public Category load(String cid) throws SQLException;
	
	public List<Category> findByParent(String pid) throws SQLException;
	
	public List<Category> findParent() throws SQLException;

	public void add(Category category) throws SQLException;
	
	public void edit(Category category) throws SQLException;
	
	public int findChildrenByParent(String pid) throws SQLException;
	
	public void delete(String cid) throws SQLException;

}

3.Mapper映射文件(切记实体类里的toString方法里边去掉类型为List的属性,要不然打印时会出现死循环的)。

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

<!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离 
注意:使用mapper代理方法开发,namespace有特殊重要的作用
-->
<mapper namespace="com.tyust.dao.CategoryDao">

  <resultMap id="CategoryResultMap" type="com.tyust.pojo.Category" >
   <id column="cid" property="cid" jdbcType="VARCHAR" />
   <result column="cname" property="cname" jdbcType="VARCHAR" />
   <result column="desc" property="desc" jdbcType="VARCHAR" />
   <!-- parent对象也是一个Category对象,该对象里只需设置其cid就行了,该cid也就是二级分类(子类)的pid -->
   <association column="pid" property="parent" javaType="com.tyust.pojo.Category">
   	<result column="pid" property="cid"/>
   </association>
   <collection column="cid" property="children" select="com.tyust.dao.CategoryDao.findByParent"/>
  </resultMap>
  
  <select id="load" parameterType="string" resultMap="CategoryResultMap">
  	select *
  	from 
  		t_category 
  	where 
  		cid=#{cid}
  </select>  
  
  <select id="findByParent" parameterType="string" resultMap="CategoryResultMap">
  	select *
  	from 
  		t_category 
  	where 
  		pid=#{cid} 
  	order by
  		orderBy
  </select>
  
  <select id="findParent" resultMap="CategoryResultMap">
  	select * 
  		from t_category 
  		where pid is null 
  		order by orderBy
  </select>
  
</mapper>
posted on 2017-10-16 18:23  CY007  阅读(210)  评论(0编辑  收藏  举报