码迷,mamicode.com
首页 > 其他好文 > 详细

MyBatis(跨表查询)

时间:2016-01-19 12:29:45      阅读:357      评论:0      收藏:0      [点我收藏+]

标签:

1、建立数据库表如下:

DROP TABLE IF EXISTS t_demo_user;
CREATE TABLE IF NOT EXISTS t_demo_user(
    userid varchar(255),
    username varchar(100),
    password varchar(100),
    PRIMARY KEY(userid)
)ENGINE=InnoDB  DEFAULT CHARSET=gbk;

insert into t_demo_user(userid, username, password) values("1001","fredric","fredric2001");


DROP TABLE IF EXISTS t_demo_role;
CREATE TABLE IF NOT EXISTS t_demo_role(
    roleid int(20) NOT NULL AUTO_INCREMENT,
    rolename varchar(100),
    userid varchar(255),
    FOREIGN KEY(userid) references t_demo_user(userid),
    PRIMARY KEY(roleid)
)ENGINE=InnoDB  DEFAULT CHARSET=gbk AUTO_INCREMENT=1 ;

insert into t_demo_role(rolename, userid) values("role1","1001"),("role2","1001");

2、建立对应的模型和接口JAVA

public class Role {
    private int roleid;
    private String rolename;
    private String userid;
public class User {
    
    private String userid;
    private String username;
    private String password;
    private List<Role> roles;
public interface IUserOperation {
    List<User> queryAfterJoin();
}

3、配置对应的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.example.mdemo.service.IUserOperation">
     <resultMap id="listMap" type="User">  
        <id column="userid" property="userid"/>  
        <result column="username" property="username"/>  
        <result column="password" property="password"/>  
        <collection property="roles" javaType="java.util.List" ofType="Role">  
            <id column="roleid" property="roleid"/>  
            <result column="rolename" property="rolename" />
        </collection>  
    </resultMap>  
    <select id="queryAfterJoin" resultMap="listMap">  
        SELECT  
          u.userid,  
          u.username,  
          u.password,
          r.roleid roleid, 
          r.rolename rolename
        FROM  
          t_demo_user u  
        LEFT JOIN  
          t_demo_role r  
        ON  
          u.userid = r.userid  
    </select>    
</mapper>

4、使用测试如下:

IUserOperation userOperation = session.getMapper(IUserOperation.class);
List<User> users = userOperation.queryAfterJoin();
            
    for(User u:users){
           System.out.println(u.getUserid());
           System.out.println(u.getUsername());
           System.out.println(u.getPassword());
           List<Role> roles = u.getRoles();
           for(Role r:roles){
               System.out.println(r.getRolename());
               System.out.println(r.getRoleid());
          }           
     }
            
     session.commit();

MyBatis(跨表查询)

标签:

原文地址:http://www.cnblogs.com/Fredric-2013/p/5141371.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!