Spring + iBatis 1对多表关系配置

SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
    "http://www.ibatis.com/dtd/sql-map-config-2.dtd">

<sqlMapConfig>
    <sqlMap resource="com/model/domain/map/BlogCategory.xml"/>
    <sqlMap resource="com/model/domain/map/BlogItem.xml"/>
</sqlMapConfig>

BlogItem.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-2.dtd">

<sqlMap>

    <typeAlias alias="BlogItem"
        type="com.model.domain.BlogItem" />
    
    <resultMap id="get-blogitem-result" class="BlogItem">
        <result property="id" column="ID" columnIndex="1" />
        <result property="title" column="TITLE" columnIndex="2" />
        <result property="content" column="CONTENT" columnIndex="3" />
        <result property="createTime" column="CREATETIME"
            columnIndex="4" />
        <result property="blogCategory.id" column="ID"/>
        <result property="blogCategory.name" column="NAME"/>
        <result property="blogCategory.description" column="DESCRIPTION"/>
    </resultMap>

    <select id="getBlogItemById" parameterClass="int" resultMap="get-blogitem-result">
        select * from BLOG_ITEMS,BLOG_CATEGORYS WHERE CATEGORYID=BLOG_CATEGORYS.ID AND ID=#value#
    </select>

</sqlMap>


BlogCategory.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-2.dtd">

<sqlMap>

    <typeAlias alias="BlogCategory"
        type="com.model.domain.BlogCategory" />
        
    <resultMap id="get-blogcategory-result" class="BlogCategory" groupBy="id">
        <result property="id" column="ID" columnIndex="1" />
        <result property="name" column="NAME" columnIndex="2" />
        <result property="description" column="DESCRIPTION"
            columnIndex="3" />
        <result property="itemList" resultMap="get-blogitem-result"/>
    </resultMap>
    
    <select id="getBlogCategoryById" parameterClass="int"
        resultMap="get-blogcategory-result">
        select CATE.ID,CATE.NAME,CATE.DESCRIPTION,ITEM.ID,ITEM.TITLE,ITEM.CONTENT,
ITEM.CREATETIME,ITEM.CATEGORYID FROM BLOG_CATEGORYS as CATE 
left outer join BLOG_ITEMS AS ITEM on CATE.ID = ITEM.CATEGORYID WHERE CATE.ID = #value#;
    </select>

</sqlMap>

-------------------
注意:
iBatis多表操作时,如果配置文件多应当注意名称冲突,最好使用一个MAP配置使用namespace命名来区
别不同的resultMap
如:
<sqlMap namespace="XXX">
<result property="itemList" resultMap="XXX.get-blogitem-result"/>


一般现在1对多,多对多关系数据库操作用Hibernate方便多了.轻量级的iBatis配置起来在SQL语法上面
要熟练才行,烦是烦点,熟练了也没什么

你可能感兴趣的:(java,spring,sql,xml,ibatis)