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 Listroles;
public interface IUserOperation { ListqueryAfterJoin();}
3、配置对应的XML文件如下:
4、使用测试如下:
IUserOperation userOperation = session.getMapper(IUserOperation.class);Listusers = userOperation.queryAfterJoin(); for(User u:users){ System.out.println(u.getUserid()); System.out.println(u.getUsername()); System.out.println(u.getPassword()); List roles = u.getRoles(); for(Role r:roles){ System.out.println(r.getRolename()); System.out.println(r.getRoleid()); } } session.commit();