(五)Mybatis总结之一对多、一对一

一对多

业务场景:张三既是java开发师又是大学老师又是LOL代练,张三拥有多个角色。

1.创建实体类UserInfo和RoleInfo

package com.qf.mybatisdemo.pojo;

import java.util.List;

public class UserInfo {
    int userId;
    String password;
    String email;
    String phone;
    String icon;
    String userName;
    String name;
    List<RoleInfo> roleInfoList;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getPassword() {
        return password;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getName() {
        return name;
    }

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

    public List<RoleInfo> getRoleInfoList() {
        return roleInfoList;
    }

    public void setRoleInfoList(List<RoleInfo> roleInfoList) {
        this.roleInfoList = roleInfoList;
    }

    @Override
    public String toString() {
        return "UserInfo{" +
                "userId=" + userId +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", phone='" + phone + '\'' +
                ", icon='" + icon + '\'' +
                ", userName='" + userName + '\'' +
                ", name='" + name + '\'' +
                ", roleInfoList=" + roleInfoList +
                '}';
    }
}

package com.qf.mybatisdemo.pojo;

import java.util.List;

public class RoleInfo {
    int roleId;
    String roleName;
    String shortName;
    List<MenuInfo> menuInfos;

    public int getRoleId() {
        return roleId;
    }

    public void setRoleId(int roleId) {
        this.roleId = roleId;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public String getShortName() {
        return shortName;
    }

    public void setShortName(String shortName) {
        this.shortName = shortName;
    }

    public List<MenuInfo> getMenuInfos() {
        return menuInfos;
    }

    public void setMenuInfos(List<MenuInfo> menuInfos) {
        this.menuInfos = menuInfos;
    }

    @Override
    public String toString() {
        return "RoleInfo{" +
                "roleId=" + roleId +
                ", roleName='" + roleName + '\'' +
                ", shortName='" + shortName + '\'' +
                ", menuInfos=" + menuInfos +
                '}';
    }
}


2.UserInfoMapper接口

package com.qf.mybatisdemo.mapper;

import com.qf.mybatisdemo.pojo.UserInfo;
import com.qf.mybatisdemo.userVo.UserVo;

import java.util.List;

public interface UserInfoMapper {
    <!--public UserVo userInfoLogin(UserVo userVo);-->
    <!--public int addUserInfo(UserVo userVo);-->
    <!--public int updateUserInfobyId(UserVo userVo);-->
    <!--public int deleteUserInfo(UserVo userVo);-->
    public UserInfo getUserInfoById(UserInfo userInfo);
}


3.创建UserInfoMapper.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.qf.mybatisdemo.mapper.UserInfoMapper"> 


    <!--column是数据表字段名,可以为同一表的任一字段,而property须为type 定义的pojo属性-->
    <!--resultMap的id,是识别此resultMap集合与其他resultMap的唯一的标识-->
    <resultMap id="UserInfoMap" type="com.qf.mybatisdemo.pojo.UserInfo">
        <id column="userid" property="userId"></id>
        <!--此id为表的主键字段-->
        <result column="password" property="password"></result>
        <result column="email" property="email"></result>
        <result column="icon" property="icon"></result>
        <result column="username" property="userName"></result>
        <result column="name" property="name"></result>
        <result column="phone" property="phone"></result>
        <!-- 集合中的property须为oftype定义的pojo对象的属性-->
        <collection property="roleInfoList" ofType="com.qf.mybatisdemo.pojo.RoleInfo">
            <id column="roleid" property="roleId"></id>
            <result column="rolename" property="roleName"></result>
            <result column="shortname" property="shortName"></result>
        </collection>
        <!--可以有多个collection,也可以在collection里面再嵌套collection-->
    </resultMap>
    
    <select id="getUserInfoById" parameterType="com.qf.mybatisdemo.pojo.UserInfo" resultMap="UserInfoMap">
    <!--此处返回值是UserInfoMap对象-->
        SELECT u.*,r.* from userinfo u,user_role ur,roleinfo r
        where u.USERID = ur.USERID and r.ROLEID = ur.ROLEID and
        u.userid = #{userId}
    </select>

</mapper>

标签中的column:要传递给select查询语句的参数,如果传递多个参数,格式为column= ” {参数名1=表字段1,参数名2=表字段2}


4.创建UserInfoMapper.xml

package com.qf.mybatisdemo;

import com.qf.mybatisdemo.dao.BaseDao;
import com.qf.mybatisdemo.mapper.RoleInfoMapper;
import com.qf.mybatisdemo.mapper.UserInfoMapper;
import com.qf.mybatisdemo.pojo.UserInfo;
import com.qf.mybatisdemo.userVo.UserVo;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import com.qf.mybatisdemo.pojo.RoleInfo;

import java.util.List;

public class MybatisDemo2 {

    BaseDao baseDao = new BaseDao();
    SqlSession sqlSession = baseDao.getSqlSession();
    UserInfoMapper userInfoMapper = sqlSession.getMapper(UserInfoMapper.class);

    @Test
    public void getUserInfoById() {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(1);
        UserInfo userInfos = userInfoMapper.getUserInfoById(userInfo);
        System.out.println(userInfos);
    }
}

记得在mybatis-config.xml添加映射
  • resultMap的作用:
    • 当数据表的字段名与实体类的属性名不同时,可以采用resultMap建立对应关系
    • 有关系(1对多,1对1关系)建立

一对一

业务场景:比如一张订单只能有一位顾客,而不能有多位顾客

1.创建OrderInfo和Consumer实体类

public class Consumer {
    int id;
    int age;
    String path;
    String name;
    
    public int getId() {
        return id;
    }

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


    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "ConsumerInfo{" +
                "id=" + id +
                ", age=" + age +
                ", path='" + path + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}


public class OrderInfo {
    int id;
    Date createTime;
    BigDecimal totalPrice;
    ConsumerInfo consumerInfo;

    public Date getCreateTime() {
        return createTime;
    }

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

    public BigDecimal getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(BigDecimal totalPrice) {
        this.totalPrice = totalPrice;
    }

    public ConsumerInfo getConsumerInfo() {
        return consumerInfo;
    }

    public void setConsumerInfo(ConsumerInfo consumerInfo) {
        this.consumerInfo = consumerInfo;
    }
    public int getId() {
        return id;
    }

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

    @Override
    public String toString() {
        return "OrderInfo{" +
                "id=" + id +
                ", createTime=" + createTime +
                ", totalPrice=" + totalPrice +
                ", consumerInfo=" + consumerInfo +
                '}';
    }
}


2.创建OrderInfoMapper接口

package com.qf.mybatisdemo.mapper;

import com.qf.mybatisdemo.pojo.OrderInfo;

import java.util.List;

public interface OrderInfoMapper {
    public List<OrderInfo> listAllOrders();
}


3.创建OrderInfoMapper.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.qf.mybatisdemo.mapper.OrderInfoMapper">
    <resultMap id="orderMap" type="com.qf.mybatisdemo.pojo.OrderInfo">
        <id column="id" property="id"></id>
        <result column="createTime" property="createTime"></result>
        <result column="totalPrice" property="totalPrice"></result>
        <association property="consumerInfo" javaType="com.qf.mybatisdemo.pojo.Consumer">
        <!--注意,javaType是指一对一的属性类型,而ofType是指映射到List中的pojo类型,所以一对一用javaType,一对多用ofType-->
            <id column="cid" property="id"></id>
            <result column="name" property="name"></result>
            <result column="age" property="age"></result>
            <result column="path" property="path"></result>
            <!--对象用association-->
        </association>
    </resultMap>
    <select id="listAllOrders" resultMap="orderMap">
        SELECT o.*,c.id cid,c.age,c.`name`,c.path from consumerinfo c,orderinfo o where c.id = o.cid
    </select>
</mapper>

4.Test

    public class TestAllOrders {
    
        BaseDao baseDao = new BaseDao();
        SqlSession sqlSession = baseDao.getSqlSession();
        <!--UserInfoMapper userInfoMapper = sqlSession.getMapper(UserInfoMapper.class);-->
        ConsumerInfoMapper consumerInfoMapper = sqlSession.getMapper(ConsumerInfoMapper.class);
        OrderInfoMapper orderInfoMapper = sqlSession.getMapper(OrderInfoMapper.class);
       
        @Test
        public void listAllOrders(){
            List<OrderInfo> orderInfos = orderInfoMapper.listAllOrders();
            System.out.println(orderInfos);
        }
    }
 
...
posted @ 2019-05-10 17:26  奇异果与奇迹果  阅读(252)  评论(0编辑  收藏  举报