mybatis详解四:一对一,一对多,多对多

一:创建UserMapper.xml 和 OrderMapper.xml文件
 1:user表
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `username` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名称',
  `birthday` timestamp NULL DEFAULT NULL COMMENT '生日',
  `sex` int(8) NULL DEFAULT NULL COMMENT '性别 0:女 1:男',
  `address` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact
INSERT INTO `user` VALUES ('1', 'lisi', '2019-01-26 21:23:30', 1, '遵义');
INSERT INTO `user` VALUES ('23', 'zhangsan', '2019-01-24 00:00:00', 2, '贵州');

SET FOREIGN_KEY_CHECKS = 1;
###### 2:order表
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS `order`;
CREATE TABLE `order`  (
  `order_id` varchar(100) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL COMMENT '订单表主键',
  `user_id` varchar(100) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
  `details` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`order_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Compact;
INSERT INTO `order` VALUES ('1', '1', '电脑');
INSERT INTO `order` VALUES ('2', '1', '手机');
SET FOREIGN_KEY_CHECKS = 1;
1:OrderMapper.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">
<!--namespace:值为对应的OrderMapper.java的全类名-->
<mapper namespace="mybatis1.mapper.OrderMapper">

    <!-- 一对多查询  -->
    <select id="getUserOrder" parameterType="String" resultMap="userOrder">
        SELECT * FROM `user` u, `order` o
        WHERE id = #{id} and u.id = o.user_id
    </select>

    <resultMap id="userOrder" type="User">
        <!--主键id映射   有多个主键可以写多个此标签-->
        <id property="id" column="id"/>
        <!--property:对应java属性  column:对应表字段-->
        <result property="username" column="username"/>
        <result property="address" column="address"/>
        <result property="birthday" column="birthday"/>
        <!--ofType:返回的集合元素对应Order.java-->
        <collection property="orderList" ofType="Order">
            <id property="orderId" column="order_id"/>
            <result property="userId" column="user_id"/>
            <result property="details" column="details"/>
        </collection>
    </resultMap>
</mapper>
 3 User.java
package mybatis1.pojo;

import java.sql.Timestamp;
import java.util.List;

/**
 * Created by user on 2019/1/24.
 */
public class User {
    private String id; //用户id
    private String username;//用户姓名
    private Timestamp birthday;//用户生日
    private int sex;//用户性别
    private String address;//用户地址
    private List<Order> orderList;//用户订单列表

    public User() {
    }

    public String getId() {
        return id;
    }

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

    public Timestamp getBirthday() {
        return birthday;
    }

    public void setBirthday(Timestamp birthday) {
        this.birthday = birthday;
    }

    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public List<Order> getOrderList() {
        return orderList;
    }

    public void setOrderList(List<Order> orderList) {
        this.orderList = orderList;
    }
}
4:Order.java
package mybatis1.pojo;

public class Order {
    private String orderId;//订单id
    private String details;//订单详情
    private int price;//订单价格
    private String id;//用户id
    private User user;//一个订单只能属于一个用户

    public Order() {
    }

    public String getOrderId() {
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }

    public String getDetails() {
        return details;
    }

    public void setDetails(String details) {
        this.details = details;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getUserId() {
        return id;
    }

    public void setUserId(String id) {
        this.id = id;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

二:创建userMapper.java和 OrderMapper.java文件
1.OrderMapper.java
package mybatis1.mapper;
import mybatis1.pojo.Order;
import mybatis1.pojo.User;
public interface OrderMapper {

    //获取用户订单 一对一查询 第一种方式
    public Order getOrderByOrderId1(Order order);
	//获取用户订单 一对一查询 第二种方式
    public Order getOrderByOrderId2(Order order);
	//获取用户通过id
    public User getUserById(String userId);
}
5:UserVo.java
package mybatis1.pojo;
import java.util.List;
public class UserVo {
    private List<String> ids;

    public List<String> getIds() {
        return ids;
    }

    public void setIds(List<String> ids) {
        this.ids = ids;
    }
}

2.UserMapper.java文件

package mybatis1.mapper;
import mybatis1.pojo.User;
import mybatis1.pojo.UserVo;
import java.util.List;
public interface UserMapper {
    //获取用户通过id
    public User getUserById(String id);
    //保存用户信息用户
    public void saveUser(User user);
    //更新用户信息
    public void updateUser(User user);
    //删除用户信息
    public void deleteUserById(String id);
    public User getUserByCondition(User user);
    //获取用户信息通过条件
    public User getUserByCondition1(User user);
    //获取用户信息更加条件
    public User getUserByCondition2(User user);
    //获取多个用户
    public List<User> getUsersByIds(UserVo userVo);

    //获取用户的所有订单  一对多查询方式
    public User getUserOrder(String userId);
}
三:创建测试用例
 //一对一  第一种方式
    @Test
    public void getOrder(){
        OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
        Order order = new Order();
        order.setOrderId("1");
        order.setUserId("1");
        order = orderMapper.getOrderByOrderId1(order);
        System.out.println(order);
    }
    //一对一  第er种方式
    @Test
    public void getOrder2(){
        OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
        Order order = new Order();
        order.setOrderId("2");
        order = orderMapper.getOrderByOrderId2(order);
        System.out.println(order);
    }

    //一对多查询
    @Test
    public void getUserOrder(){
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User userOrder = userMapper.getUserOrder("1");
        System.out.println(userOrder);
    }

总结

1:至于mybatis的懒加载什么的就不写了,因为在项目中很少使用了。现在都是使用Redis替代了懒加载。
2:后期将写出Spring与mybatis的整合,在哪才会写mybatis事物相关的知识

你可能感兴趣的:(mybatis)