转自:http://blog.csdn.net/jefry_xdz/article/details/8767358
创建两张表:一张是用户,一张是用户所对应的移动手机,一户用户可以有部移动手机。
这是用户t_user表
这是移动电话t_mobile表
在Java实体对象对中,一对多可以根据List和Set来实现,两者在mybitis中都是通过collection标签来配合使用,稍后会做详细配置介绍
创建表对应的JavaBean对象
Mobile Bean
- public class Mobile {
- private int id;
- private String telnumber;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getTelnumber() {
- return telnumber;
- }
- public void setTelnumber(String telnumber) {
- this.telnumber = telnumber;
- }
- }
User Bean
- package com.jefry;
- import java.util.List;
- public class User {
- private int id;
- private String userName;
- private String password;
- private List<Mobile> mobiles; //这里也可以是Set集合
- public List<Mobile> getMobiles() {
- return mobiles;
- }
- public void setMobiles(List<Mobile> mobiles) {
- this.mobiles = mobiles;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- }
在上一篇的基础上改写映射文件:
- <?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="user">
- <resultMap id="userResultMap" type="User">
- <id property="id" column="id" javaType="int" jdbcType="INTEGER" />
- <result property="userName" column="name" javaType="string" jdbcType="VARCHAR"/>
- <result property="password" column="pass" javaType="string" jdbcType="VARCHAR"/>
- <collection property="mobiles" column="userid" ofType="Mobile">
- <id property="id" column="id" javaType="int" jdbcType="INTEGER"/>
- <result property="telnumber" column="telnumber" javaType="string" jdbcType="VARCHAR"/>
- </collection>
- </resultMap>
- <!--多表查询操作-->
- <select id="selectUser" parameterType="int" resultMap="userResultMap" >
- <!--分别为mobile的主键id与user的主键id赋值别名,避免因为两个表字段名称相同而注入到对应对象名称冲突-->
- select m.id m_id,m.telnumber,u.id u_id,u.name,u.pass from t_mobile m,t_user u where m.userid = u.id and u.id = #{id}
- </select>
- </mapper>
最后,通过测试OK
- public class Test {
- static String resource = "mybatis-config.xml";
- public static void main(String[] args) throws IOException {
- InputStream inputStream = Resources.getResourceAsStream(resource);
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- SqlSession session = sqlSessionFactory.openSession();
- try {
- User user = session.selectOne("user.selectUser", 1);
- List<Mobile> mobiles = user.getMobiles();
- for(Mobile mobile : mobiles) {
- System.out.println("user:" + user.getUserName() + ",tel:" + mobile.getTelnumber());
- }
- } finally {
- session.close();
- }
- }
- }