1. 程式人生 > >Mybatis多對多關聯查詢

Mybatis多對多關聯查詢

mybatis3.0添加了association和collection標籤專門用於對多個相關實體類資料進行級聯查詢,但仍不支援多個相關實體類資料的級聯儲存和級聯刪除操作。因此在進行實體類多對多對映表設計時,需要專門建立一個關聯物件類對相關實體類的關聯關係進行描述。下文將以“User”和“Group”兩個實體類之間的多對多關聯對映為例進行CRUD操作。

建立user表,對應實體類”User”,建表語句如下:

Sql程式碼

 CREATE TABLE `user` (  
      `id` int(11) NOT NULL auto_increment,  
      `name`
varchar(40) collate utf8_unicode_ci default NULL, `password` varchar(20) collate utf8_unicode_ci default NULL, `createtime` timestamp NULL default CURRENT_TIMESTAMP, PRIMARY KEY (`id`) )

建立group_info表,對應實體類”Group”,建表語句如下:

Sql程式碼

    CREATE TABLE `group_info` (  
      `id`
int(11) NOT NULL auto_increment, `name` varchar(40) collate utf8_unicode_ci default NULL, `createdate` timestamp NULL default CURRENT_TIMESTAMP, `state` int(1) default '0' COMMENT '0:可見;1:不可見', PRIMARY KEY (`id`) )

建立user_group表,對應實體類”UserGroupLink”(該類為User和Group兩個實體類之間的關係描述),建表語句如下:

Sql程式碼

    CREATE TABLE `user_group` (  
      `user_id` int(11) default NULL,  
      `group_id` int(11) default NULL,  
      `createdate` timestamp NULL default CURRENT_TIMESTAMP,  
      KEY `FK_user_group_user_id` (`user_id`),  
      KEY `FK_user_group_group_id` (`group_id`),  
      CONSTRAINT `FK_user_group_group_id` FOREIGN KEY (`group_id`) REFERENCES `group_info` (`id`),  
      CONSTRAINT `FK_user_group_user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)  
    )   

建立實體類User,程式碼如下:
Java程式碼

  package com.xxt.ibatis.dbcp.domain;  

    import java.util.Date;  
    import java.util.List;  

    /** 
     * @describe: User實體類 
     * @author:    Nirvana 
     * @version:   V1.0  2011-3-11下午06:06:49 create 
     */  

    public class User {  

        private long id;  

        private String name;  

        private String password;  

        private Date createTime;  

        private List<Group> group;  

        public Date getCreateTime() {  
            return createTime;  
        }  

        public void setCreateTime(Date createTime) {  
            this.createTime = createTime;  
        }  

        public long getId() {  
            return id;  
        }  

        public void setId(long id) {  
            this.id = id;  
        }  

        public String getName() {  
            return name;  
        }  

        public void setName(String name) {  
            this.name = name;  
        }  

        public String getPassword() {  
            return password;  
        }  

        public void setPassword(String password) {  
            this.password = password;  
        }  

        public List<Group> getGroup() {  
            return group;  
        }  

        public void setGroup(List<Group> group) {  
            this.group = group;  
        }  
    }  

建立實體類Group,程式碼如下:
Java程式碼

 package com.xxt.ibatis.dbcp.domain;  

    import java.util.Date;  
    import java.util.List;  

    /** 
     * @describe: Group實體類 
     * @author: Nirvana 
     * @version: V1.0 2011-3-7下午08:10:29 create 
     */  
    public class Group {  

        private long id;  

        private String name; // 組名  

        private Date createTime;  

        private int state; // 0可見狀態 1不可見狀態  

        private List<User> user;  

        public Date getCreateTime() {  
            return createTime;  
        }  

        public void setCreateTime(Date createTime) {  
            this.createTime = createTime;  
        }  

        public long getId() {  
            return id;  
        }  

        public void setId(long id) {  
            this.id = id;  
        }  

        public String getName() {  
            return name;  
        }  

        public void setName(String name) {  
            this.name = name;  
        }  

        public int getState() {  
            return state;  
        }  

        public void setState(int state) {  
            this.state = state;  
        }  

        public List<User> getUser() {  
            return user;  
        }  

        public void setUser(List<User> user) {  
            this.user = user;  
        }  

    }  

建立實體類UserGroupLink,用於描述User和Group之間的對應關係,程式碼如下:
Java程式碼

 package com.xxt.ibatis.dbcp.domain;  

    import java.util.Date;  

    /** 
     * @describe: 描述User和Group之間的對映關係 
     * @author: Nirvana 
     * @version: V1.0 2011-3-11下午02:57:52 create 
     */  
    public class UserGroupLink {  

        private User user;  

        private Group group;  

        private Date createTime;  

        public Date getCreateTime() {  
            return createTime;  
        }  

        public void setCreateTime(Date createTime) {  
            this.createTime = createTime;  
        }  

        public Group getGroup() {  
            return group;  
        }  

        public void setGroup(Group group) {  
            this.group = group;  
        }  

        public User getUser() {  
            return user;  
        }  

        public void setUser(User user) {  
            this.user = user;  
        }  
    }  

建立user實體類的對映檔案user.map.xml,程式碼如下:
Xml程式碼

 <?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">  
    <mapper namespace="com.xxt.ibatis.dbcp.domain.User">  
        <resultMap type="User" id="userMap">  
            <id property="id" column="id" />  
            <result property="name" column="name" />  
            <result property="password" column="password" />  
            <result property="createTime" column="createtime" />  
        </resultMap>  

        <resultMap type="User" id="userGroupMap" extends="userMap">  
            <collection property="groups" ofType="Group">  
                <id property="id" column="goupId" />  
                <result property="name" column="groupName" />  
                <result property="state" column="state" />  
                <result property="createTime" column="groupCreateTime" />  
            </collection>  
        </resultMap>  


        <!-- 根據user表中的id查詢使用者資訊 -->  
        <select id="selectUser" parameterType="long" resultMap="userMap">  
            select * from user where id = #{id}  
        </select>  

        <!-- 根據user表中的id查詢使用者和組資訊 -->  
        <select id="selectUserGroup" parameterType="long"  
            resultMap="userGroupMap">  
            select u.id,u.name,u.password,u.createtime, gi.id as  
            goupId,gi.name as groupName, gi.createdate as groupCreateTime,  
            gi.state from user u left join user_group ug on u.id=ug.user_id  
            left join group_info gi on ug.group_id=gi.id where u.id = #{id}  
        </select>  

        <!-- 插入使用者資訊 -->  
        <insert id="saveUser" parameterType="User" keyProperty="id"  
            useGeneratedKeys="true">  
            insert into user(name,password) values(#{name},#{password})  
        </insert>  

        <!-- 儲存使用者和組之間的關係資訊 -->  
        <insert id="saveRelativity" parameterType="UserGroupLink">  
            insert into user_group(user_id,group_id)  
            values(#{user.id},#{group.id})  
        </insert>  

        <select id="selectAllUser" resultMap="userMap">  
            select * from user  
        </select>  

    </mapper>  

建立group實體類的對映檔案group.map.xml,程式碼如下:

Xml程式碼

  <?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">  
    <mapper namespace="com.xxt.ibatis.dbcp.domain.Group">  
        <resultMap type="Group" id="groupMap">  
            <id property="id" column="id" />  
            <result property="name" column="name" />  
            <result property="createTime" column="createdate" />  
        </resultMap>  

        <resultMap type="Group" id="groupUserMap" extends="groupMap">  
            <collection property="users" ofType="User">  
                <id property="id" column="userId" />  
                <result property="name" column="userName" />  
                <result property="password" column="password" />  
                <result property="createTime" column="userCreateTime" />  
            </collection>  
        </resultMap>  


        <!-- 根據Group表中的id或name查詢組資訊和組內使用者資訊 -->  
        <select id="selectGroupUser" parameterType="Group"  
            resultMap="groupUserMap">  
            select u.id as userId,u.name as userName,  
            u.password,u.createtime as userCreateTime,  
            gi.id,gi.name,gi.createdate,gi.state from group_info gi left  
            join user_group ug on gi.id=ug.group_id left join user u on  
            uug.user_id=u.id  
            <where>  
                <!--當id為初始值0,不再使用id作為查詢條件 -->  
                <if test="id != 0  ">gi.id=#{id}</if>  
                <!-- 當name為空或為空串時,不再使用name作為查詢條件 -->  
                <if test="name != null and name != ''">  
                    or gi.name = #{name}  
                </if>  
            </where>  
        </select>  

        <!-- 根據id查詢group組資訊 -->  
        <select id="selectGroup" parameterType="Date"  
            resultMap="groupMap">  
            select * from group_info where id=#{group_id}  
        </select>  

        <!--根據name查詢group組資訊  -->  
        <select id="getGroupByName" parameterType="String"  
            resultMap="groupMap">  
            select * from group_info where name=#{name}  
        </select>  

        <!-- 插入組資訊 -->  
        <insert id="saveGroup" parameterType="Group" keyProperty="id"  
            useGeneratedKeys="true">  
            insert into group_info(name) values(#{name})  
        </insert>  

        <!-- 刪除組與組內成員之間的對應關係 -->  
        <delete id="deleteGroupUser" parameterType="UserGroupLink">  
            delete from user_group  
            <where>  
                <if test="user.id != 0">user_id = #{user.id}</if>  
                <if test="group.id != 0">and group_id = #{group.id}</if>  
            </where>  
        </delete>  

        <!--根據組id或者組name刪除組資訊 -->  
        <delete id="deleteGroup" parameterType="Group">  
            delete from group_info  
            <where>  
                <if test="id!=0">id=#{id}</if>  
                <if test="name!=null || name!=''">and name=#{name}</if>  
            </where>  
        </delete>  

        <!-- 更新根據組id或者組name更新組狀態 -->  
        <update id="updateGroupState" parameterType="Group">  
            update group_info set state=#{state}  
            <where>  
                <if test="id!=0">id=#{id}</if>  
                <if test="name!=null || name!=''">and name=#{name}</if>  
            </where>  
        </update>  
    </mapper>  

建立Mbatis總配置檔案salMapConfig.xml,程式碼如下:

Xml程式碼

   <?xml version="1.0" encoding="UTF-8"?>  
    <!DOCTYPE configuration   
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"   
        "http://mybatis.org/dtd/mybatis-3-config.dtd">  
    <configuration>  
        <properties resource="jdbc.properties" />  

        <typeAliases>  
            <typeAlias type="com.xxt.ibatis.dbcp.domain.User" alias="User" />  
            <typeAlias type="com.xxt.ibatis.dbcp.domain.Group"  
                alias="Group" />  
            <typeAlias type="com.xxt.ibatis.dbcp.domain.UserGroupLink"  
                alias="UserGroupLink" />  
        </typeAliases>  

        <environments default="development">  
            <environment id="development">  
                <transactionManager type="JDBC" />  
                <dataSource type="UNPOOLED">  
                    <property name="driver" value="${driver}" />  
                    <property name="url" value="${url}" />  
                    <property name="username" value="${username}" />  
                    <property name="password" value="${password}" />  
                </dataSource>  
            </environment>  
        </environments>  

        <mappers>  
            <mapper resource="com/xxt/ibatis/dbcp/domain/user.map.xml" />  
            <mapper resource="com/xxt/ibatis/dbcp/domain/group.map.xml" />  
        </mappers>  
    </configuration>  

測試用例,程式碼如下:

Java程式碼

  package com.xxt.ibatis.dbcp.test;  

    import java.io.Reader;  
    import java.text.SimpleDateFormat;  
    import java.util.List;  

    import org.junit.AfterClass;  
    import org.junit.BeforeClass;  
    import org.junit.Test;  

    import org.apache.ibatis.io.Resources;       
    import org.apache.ibatis.session.SqlSession;  
    import org.apache.ibatis.session.SqlSessionFactory;  
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;  

    import com.xxt.ibatis.dbcp.domain.Group;  
    import com.xxt.ibatis.dbcp.domain.User;  
    import com.xxt.ibatis.dbcp.domain.UserGroupLink;  

    /** 
     * @describe: 測試用例 
     * @author:    Nirvana 
     * @version:   V1.0  2011-3-4下午03:21:17 create 
     */  
    public class IbatisUserTest {  

        private final static String IBATIS_CONFIG_XML  = "sqlMapConfig.xml";   
        private static SqlSession session;  
        private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd k:mm:ss");  

        @BeforeClass  
        public static void setUpBeforeClass() throws Exception {  
             Reader reader = Resources.getResourceAsReader(IBATIS_CONFIG_XML);  //讀取ibatis配置檔案  
             SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);  
              session = sqlMapper.openSession(true);  
              session.commit(false); //將預設提交事務屬性設定為否  
        }  


        //儲存使用者資訊  
        @Test  
        public void saveUserTest(){  
            User user = new User();  
            user.setName("張三");  
            user.setPassword("123456");  
            session.insert("com.xxt.ibatis.dbcp.domain.User.saveUser", user);  
        }  

        //獲取使用者資訊  
        @Test  
        public void getUserTest(){  
            User user = (User) session.selectOne("com.xxt.ibatis.dbcp.domain.User.selectUser", 1L);  
            System.out.println("使用者名稱: "+user.getName());  
            System.out.println("使用者密碼:  "+user.getPassword());  
            System.out.println("使用者建立日期:"+sdf.format(user.getCreateTime()));  
        }  

        //獲取使用者和使用者所在組資訊  
        @Test  
        public void getUserAndGroupTest(){  
             User  user =  (User)session.selectOne("com.xxt.ibatis.dbcp.domain.User.selectUserGroup", 4L);  

             System.out.println(user.getName() +"所屬組資訊:");  
            for(Group group : user.getGroups() ){  
                System.out.println("    組名:"+group.getName()+",組建立時間:"+sdf.format(group.getCreateTime()));  
            }  


        }  

        //儲存使用者和使用者所在組資訊  
        //當用戶所在組不存在時,建立該組,並生成對映關係  
        @Test  
        public void saveUserAndGroupTest(){  
            User user = new User();  
            user.setName("無常鬼");  
            user.setPassword("wuchang");  
            session.insert("com.xxt.ibatis.dbcp.domain.User.saveUser", user);  

            Group groupImpl = (Group)session.selectOne("com.xxt.ibatis.dbcp.domain.Group.getGroupByName","使用者組4");//獲取組例項  
            UserGroupLink ugl = new UserGroupLink();//宣告User和Group實體間對映關係例項  

            //查詢到的組例項為空時的邏輯處理  
            if(groupImpl == null){  
                 Group group = new Group();  
                 group.setName("使用者組4");  
                session.insert("com.xxt.ibatis.dbcp.domain.Group.saveGroup", group);//持久化建立好的組例項  

                //設定對映關係例項相關的屬性  
                ugl.setUser(user);  
                ugl.setGroup(group);  
                session.insert("com.xxt.ibatis.dbcp.domain.User.saveRelativity",ugl);//持久化對映關係實力  

            }else{  
                ugl.setGroup(groupImpl);  
                ugl.setUser(user);  
                session.insert("com.xxt.ibatis.dbcp.domain.User.saveRelativity",ugl);  
            }  
        }  


        //刪除組資訊的同時,取消組內所有的成員與該組的關聯關係  
        @Test  
        public void deleteGroupTest(){  
            Group group = new Group();  
            //group.setId(1L);  //以組id作為查詢條件  
            group.setName("使用者組1"); //以組name作為查詢條件  
            Group groupImpl = (Group)session.selectOne("com.xxt.ibatis.dbcp.domain.Group.selectGroupUser",group);//獲取組例項  

            //組例項存在時  
            if(groupImpl != null){  

                List<User> users = groupImpl.getUsers();  

              //檢視使用者組1中是否存在使用者  
                if(users != null && users.size() > 0){  

                    //存在使用者時,先刪除組與使用者的對應關係  
                    UserGroupLink ugl = new UserGroupLink();  
                    for(User user : users){  
                       ugl.setUser(user);  
                       ugl.setGroup(groupImpl);  
                       session.delete("com.xxt.ibatis.dbcp.domain.Group.deleteGroupUser",ugl );  
                    }   
                }  
                //刪除組資訊  
                session.delete("com.xxt.ibatis.dbcp.domain.Group.deleteGroup", groupImpl);  

            }else{  
                throw new RuntimeException("查詢的組不存在!!");  
            }  


        }  


        //更新組狀態,當組狀態由可見狀態變成不可見時,取消該組下的使用者與該組的對映關係  
        @Test  
        public void updateGroupStateTest(){  
            Group group = new Group();  
            group.setName("使用者組2");  
            Group groupImpl = (Group) session.selectOne("com.xxt.ibatis.dbcp.domain.Group.selectGroupUser",group);  

            if(groupImpl != null){  
                int state = groupImpl.getState() == 1 ? 0 : 1;  


                //組狀態由0變成1時,即由可見變為不可見  
                if(state == 1){  
                    List<User> users = groupImpl.getUsers();  
               //檢視使用者組2中是否存在使用者  
                    if(users != null && users.size() > 0){  

                        //存在使用者時,刪除組與使用者的對應關係  
                        UserGroupLink ugl = new UserGroupLink();  
                        for(User user : users){  
                           ugl.setUser(user);  
                           ugl.setGroup(groupImpl);  
                           session.delete("com.xxt.ibatis.dbcp.domain.Group.deleteGroupUser",ugl );  
                        }   
                    }  
                }   

                //更新組狀態  
                groupImpl.setState(state);  
            }  
            else{  
                throw new RuntimeException("查詢的組不存在!!");  
            }  

        }  

        @AfterClass  
        public static void tearDownAfterClass() throws Exception {  
          if(session != null){  
             session.commit(); //提交事務  
             session.close(); //關閉連線  
          }  
        }   
    }