欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mybatis多表连接多对多例子工程(补充易百教程缺失部分)

程序员文章站 2022-03-10 17:09:19
...

一、工程目录如下:

Mybatis多表连接多对多例子工程(补充易百教程缺失部分)

 二、

(一)Main.java

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

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.yiibai.maper.GroupMaper;
import com.yiibai.maper.UserGroupMaper;
import com.yiibai.maper.UserMaper;
import com.yiibai.pojo.Group;
import com.yiibai.pojo.User;
import com.yiibai.pojo.UserGroup;

public class Main {
    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    static {
        try {
            reader = Resources.getResourceAsReader("config/Configure.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSession() {
        return sqlSessionFactory;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // testAddGroup();
        // testAddUser();
        //testAddUserGroup();
        testGetGroupAndUsers();
        
    }
    
    /*
    public static void testGetGroupAndUsers() {
        UserGroup userGroup = new UserGroup();
        SqlSession session = sqlSessionFactory.openSession();
        try {
            GroupMaper groupMaper = session.getMapper(GroupMaper.class);
            Group group = groupMaper.getGroup(1);
            System.out.println("Group => " + group.getGroupName());
            List<User> users = group.getUsers();
            for (User user : users) {
                System.out.println("\t:" + user.getId() + "\t"
                        + user.getUsername());
            }
        } finally {
            session.close();
        }
    }
    */
    public static void testGetGroupAndUsers() {
        UserGroup userGroup = new UserGroup();
        userGroup.getUserId();
        SqlSession session = sqlSessionFactory.openSession();
        try {
            GroupMaper groupMaper = session.getMapper(GroupMaper.class);
            Group group = groupMaper.getGroups(1);
            System.out.println("Group => " + group.getGroupName());
            List<User> users = group.getUsers();
            for (User user : users) {
                System.out.println("\t:" + user.getId() + "\t"
                        + user.getUsername());
            }
        } finally {
            session.close();
        }
    }
    
/*
    public static void testAddUserGroup() {
        UserGroup userGroup = new UserGroup();
        userGroup.setGroupId(1);
        userGroup.setUserId(2);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            UserGroupMaper userGroupMaper = session
                    .getMapper(UserGroupMaper.class);
            userGroupMaper.insertUserGroup(userGroup);

            session.commit();
        } finally {
            session.close();
        }

    }
*/

    public static void testAddUser() {
        // TODO Auto-generated method stub
        SqlSession session = sqlSessionFactory.openSession();
        try {
            User user = new User();
            user.setUsername("User-name-1");
            user.setMobile("13838009988");
            UserMaper userMaper = session.getMapper(UserMaper.class);
            userMaper.insertUser(user);
            session.commit();
            // System.out.println(user.getGroupId());
        } finally {
            session.close();
        }
    }

    public static void testAddGroup() {
        // TODO Auto-generated method stub
        SqlSession session = sqlSessionFactory.openSession();
        try {
            Group group = new Group();
            group.setGroupName("用户组-1");
            GroupMaper groupMapper = session.getMapper(GroupMaper.class);
            groupMapper.insertGroup(group);
            session.commit();
            System.out.println(group.getGroupId());
        } finally {
            session.close();
        }
    }
}

(二)GroupMaper.java

package com.yiibai.maper;

import com.yiibai.pojo.Group;

public interface GroupMaper {
    
    public Group getGroups(int groupId);
    
    public Group insertGroup(Group group);
}

(三)UserGroupMaper.java

package com.yiibai.maper;

import java.util.List;

import com.yiibai.pojo.Group;
import com.yiibai.pojo.User;
import com.yiibai.pojo.UserGroup;

public interface UserGroupMaper {
    public User getUsersByGroupId(int groudId);
    public List<Group> getGroupListByUserId(int userId);
    public List<User> getUserListByGroupId(int groupId);
    
    //public UserGroup insertUserGroup(UserGroup userGroup);
    public Group getGroupsByUserId(int userId);
}

(四)UserMaper .java

package com.yiibai.maper;

import java.util.List;

import com.yiibai.pojo.User;


/**
 * @author wuchao
 * @time 上午9:44:06
 *
 */
public interface UserMaper {

    public User getUser(int userId);
    public User insertUser(User user);
    public List<User> getAllUserGroupe();
}

(五)GroupMaper.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.yiibai.maper.GroupMaper">

	<parameterMap type="Group" id="parameterGroupMap">
		<parameter property="groupId"/>
		<parameter property="groupName"/>
	</parameterMap>
	<insert id="insertGroup" parameterMap="parameterGroupMap">
		INSERT INTO `group` (group_name)
		VALUES(#{groupName}); 
	</insert>

	<resultMap type="Group" id="resultGroupMap_1">
		<result property="id" column="id" />
		<result property="groupName" column="group_name" />
		<collection property="users" column="group_id"
			select="com.yiibai.maper.UserGroupMaper.getUsersByGroupId" />
	</resultMap>
	<select id="getGroups" resultMap="resultGroupMap_1"
		parameterType="int">
		SELECT *
		FROM `group`
		WHERE group_id=#{id}
	</select>
</mapper>	

(六)UserGroupMaper.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.yiibai.maper.UserGroupMaper">
	<parameterMap type="UserGroup" id="parameterUserGroupMap">
		<parameter property="userId"/>
		<parameter property="groupId"/>
	</parameterMap>
	
	<insert id="insertUserGroup"  parameterMap="parameterUserGroupMap">
		INSERT INTO user_group(user_id, group_id)
		VALUES(#{userId},#{groupId})
	</insert>
	
	<!-- 根据一个用户组ID,查看这个用户组下的所有用户 -->
	<resultMap type="User" id="resultUserMap_2">
		<result property="id" column="id"/>
		<result property="username" column="username"/>
		<result property="mobile" column="mobile"/>
	</resultMap>
	
	<select id="getUsersByGroupId" resultMap="resultUserMap_2" parameterType="int">
		SELECT u.*, ug.group_id
		FROM user u, user_group ug
		WHERE u.id=ug.user_id AND ug.group_id=#{group_id}
	</select>
	
	<!-- 根据一个用户ID,查看这个用户所对应的组-->
	<resultMap type="Group" id="resultGroupMap_2">
		<result property="groupId" column="group_id"/>
		<result property="groupName" column="group_name"/>
	</resultMap> 
	
	<select id="getGroupsByUserId" resultMap="resultGroupMap_2" parameterType="int">
		SELECT g.*, u.user_id
		FROM group g, user_group u
		WHERE g.group_id=u.group_id AND u.user_id=#{user_id}
	</select>
</mapper>	

(七)UserMaper.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.yiibai.maper.UserMaper">
	<parameterMap type="User" id="parameterUserMap">
		<parameter property="id"/>
		<parameter property="username"/>
		<parameter property="mobile"/>
	</parameterMap>
	
	<insert id="insertUser" parameterMap="parameterUserMap">	
		INSERT INTO user(username,mobile)
		VALUES(#{username},#{mobile});
	</insert>   
	
	<resultMap type="User" id="resultUser">
		<result property="id" column="group_id"/>
		<result property="name" column="name"/>
		<collection property="groups" column="id" select="com.yiibai.maper.UserGroupMaper.getGroupsByUserId"/>
	</resultMap>
	
	<select id="getUsers" resultMap="resultUser" parameterType="int">
		SELECT *
		FROM user
		WHERE id=#{id}
	</select>    
</mapper>

(八)Group.java

package com.yiibai.pojo;

import java.util.List;

/** 
 * @describe: Group
 * @author: Yiibai 
 * @version: V1.0
 * @copyright http://www.yiibai.com
 */  
public class Group {
	private int groupId;
	private String groupName;
	private List<User> users;
	
	public List<User> getUsers() {
		return users;
	}
	public void setUsers(List<User> users) {
		this.users = users;
	}
	public int getGroupId() {
		return groupId;
	}
	public void setGroupId(int groupId) {
		this.groupId = groupId;
	}
	public String getGroupName() {
		return groupName;
	}
	public void setGroupName(String groupName) {
		this.groupName = groupName;
	}
	
}

(九)User.java

package com.yiibai.pojo;

import java.util.List;

/** 
 * @describe: User
 * @author: Yiibai 
 * @version: V1.0
 * @copyright http://www.yiibai.com
 */  
public class User {
	private int id;
	private String username;
	private String mobile;
	private List<Group> groups;
	public List<Group> getGroups() {
		return groups;
	}
	public void setGroups(List<Group> groups) {
		this.groups = groups;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	
}

(十)UserGroup.java

package com.yiibai.pojo;

public class UserGroup {
	private int userId;  
    private int groupId;
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public int getGroupId() {
		return groupId;
	}
	public void setGroupId(int groupId) {
		this.groupId = groupId;
	}
 
    
}

(十一)Configure.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>
	<typeAliases>
		<typeAlias alias="User" type="com.yiibai.pojo.User" />
		<typeAlias alias="UserGroup" type="com.yiibai.pojo.UserGroup" />
		<typeAlias alias="Group" type="com.yiibai.pojo.Group" />
	</typeAliases>
	<environments default="development">
	    <environment id="development">
		<transactionManager type="JDBC" />
			<dataSource type="POOLED">  
                            <property name="driver" value="com.mysql.jdbc.Driver" />
			    <property name="url" value="jdbc:mysql://localhost:3306/yiibai" />
			    <property name="username" value="root" />
			    <property name="password" value="root" />
                       </dataSource>
		</environment>
	</environments>

	<mappers>
	     <!-- // power by http://www.yiibai.com -->
	     <mapper resource="com/yiibai/maper/UserMaper.xml" />
		 <mapper resource="com/yiibai/maper/GroupMaper.xml" />
		 <mapper resource="com/yiibai/maper/UserGroupMaper.xml" />
	</mappers>
</configuration>

 

相关标签: Mybatis