Mybatis进阶之表之间的关系

Mybatis

输入映射 支持的类
    八大基础数据类型
    list map pojo
    包装类型
    可以通过对象导航的方式不断向下获取
    例如:#{user.username}
输出映射
    八大基础数据类型
    list map pojo
    输出包装类型时 需要自动映射字段

根据ID查找对象

User.java

package com.lanou.bean;

public class User {
    private int id;
    private String name;
    private String password;
    private String sex;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", password=" + password + ", sex=" + sex + "]";
    }

}

根据ID查找对象

public interface UserDao {
    // 根据ID查找对象
    public User findUserById(int id);

}

UserDao.xml




<mapper  namespace="com.lanou.dao.UserDao">
    <select id="findUserById" parameterType="Integer" resultType="User" >
        select * from User where id = #{param}
    select>
mapper>

MybatisTest.java

public class MybatisTest {
    @Test
    public void test() throws IOException {
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = builder.build(inputStream);
        SqlSession session = factory.openSession();
        UserDao dao = session.getMapper(UserDao.class);
        User user = dao.findUserById(6);
        System.out.println(user);
    }
}

使用包装类

UserDataObj.java

package com.lanou.bean;

public class UserDataObj {

    private User user;

    public User getUser() {
        return user;
    }

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

    @Override
    public String toString() {
        return "UserDataObj [user=" + user + "]";
    }
}

UserDao.java

public interface UserDao {
    // 根据ID查找对象
    public User findUserById(int id);
    // 使用包装类添加对象
    public int insertUserByUserDataObj(UserDataObj obj);
}

UserDao.xml

"com.lanou.dao.UserDao">
    <select id="findUserById" parameterType="Integer" resultType="User" >
        select * from User where id = #{param}
    select>

    "insertUserByUserDataObj" parameterType="UserDataObj">
        insert into user values (
        null,
        #{user.name},
        #{user.password},
        #{user.sex}
        )
    

MybatisTest.java

public void test1() throws IOException {
    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
    SqlSessionFactory factory = builder.build(inputStream);
    SqlSession session = factory.openSession();
    User user = new User();
    user.setName("刘邦");
    user.setPassword("12345");
    user.setSex("男");
    UserDataObj obj = new UserDataObj();
    obj.setUser(user);
    UserDao dao = session.getMapper(UserDao.class);
    int i = dao.insertUserByUserDataObj(obj);
    System.out.println(i);
    session.commit();
}

标签根据多个id查询一堆user

根据一堆id查询user, id in (1,2,3) foreach标签用来遍历参数
collection 指定被遍历的集合
item 每一次遍历得到的变量seperator
open 开始标记
close 结束标记

UserDao.java

public interface UserDao {
    // 根据ID查找对象
    public User findUserById(int id);
    // 使用包装类添加对象
    public int insertUserByUserDataObj(UserDataObj obj);

    public List selectUserByIds(Integer[] ids);
}

UserDao.xml

当我们传的参数是一个数组时
java中没有对应的包装类型
可以写object 也可以不写
parameterType 作用是规范书写 怕你转错类型

遍历数组时 参数的名字是固定的 array
遍历ArrayList时 参数的名字是固定的 list
Mybatis参数映射的原理
其实就是把你传过来的参数转成map 以键值对的方式传递
所以基础数据类型的获取方式是${value} value也是固定的


<select id="selectUserByIds" parameterType="java.lang.Object" resultType="User">
    select * from user where id in
    <foreach collection="array" item="item" separator="," open="(" close=")">
        #{item}
    foreach>
select>

MybatisTest.java

public void test2() throws IOException {
    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
    SqlSessionFactory factory = builder.build(inputStream);
    SqlSession session = factory.openSession();
    Integer[] ids = new Integer[] {6,10,11}; 
    UserDao dao = session.getMapper(UserDao.class);
    List list = dao.selectUserByIds(ids);
    for (User user : list) {
        System.out.println(user);
    }
}

将参数Integer[]改为List

UserDao.java

public interface UserDao {
    // 根据ID查找对象
    public User findUserById(int id);
    // 使用包装类添加对象
    public int insertUserByUserDataObj(UserDataObj obj);

    public List selectUserByIds(List ids);
}

UserDao.xml

<select id="selectUserByIds" parameterType="java.util.List" resultType="User">
    select * from user where id in
    <foreach collection="list" item="item" separator="," open="(" close=")">
        #{item}
    foreach>
select>

MybatisTest.java

public void test2() throws IOException {
    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
    SqlSessionFactory factory = builder.build(inputStream);
    SqlSession session = factory.openSession();
    List<Integer> list = new ArrayList<>();
    list.add(6);
    list.add(10);
    UserDao dao = session.getMapper(UserDao.class);
    List<User> list2 = dao.selectUserByIds(list);
    for (User user : list2) {
        System.out.println(user);
    }
}

常用标签

条件判断

根据姓名和性别同时查询

UserDao.java

public interface UserDao {
    // 根据ID查找对象
    public User findUserById(int id);
    // 使用包装类添加对象
    public int insertUserByUserDataObj(UserDataObj obj);
    // 根据一组id进行查询
    public List selectUserByIds(List ids);
    // 根据姓名和性别同时进行查询
    public User getUser(User u);
}

UserDao.xml

之所以需要1=1 因为如果name为空 则不加1=1时 sql语句为
select * from user where and sex = #{sex} 
或sex为空 
select * from user where and name = #{sex} 
当加上1=1select * from user where 1=1 and sex = #{sex} 
select * from user where 1=1 and name = #{name} 
select * from user where 1=1 and name = #{name} and sex = #{sex} 


<select id="getUser" parameterType="User" resultType="User">
    select * from user where 1=1
    <if test="name != null and name != ''">
        and name = #{name}
    if>
    <if test="sex != null and name !=''">
        and sex = #{sex}
    if>
select>

UserDao.xml

public void test3() throws IOException {
    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
    SqlSessionFactory factory = builder.build(inputStream);
    SqlSession session = factory.openSession();
    User user = new User();
    user.setName("刘邦");
    user.setSex("男");
    UserDao dao = session.getMapper(UserDao.class);
    User user2 = dao.getUser(user);
    System.out.println(user2);
}

where标签

where标签的作用 执行内部的逻辑并拼接到外部的sql中 会自动删除第一个and

<select id="getUser" parameterType="User" resultType="User">
    select * from user 
    <where>
        <if test="name != null and name != ''">
            and name = #{name}
        if>
        <if test="sex != null and name !=''">
            and sex = #{sex}
        if>
    where>
select>

sql标签

如果有很多重复的sql语句 没有必要每次写 可以对它进行抽取
"selectUser">
    select * from User


<select id="findUserById" parameterType="int" resultType="com.lanou.bean.User">
    "selectUser"> where id = #{param}
select>

一对多查询

在数据库中建立两张表 分别为user和orders user为主表 orders为从表 orders中有一个键是外键
参照user主表中的id

AutoMapping 设为true 可以自动将列名与属性名称对应数据映射
    一对一 javaType用来指定集合内元素的类型 必须写 否则空指针异常

实现:
    在查询user数据时自动查询出对应的orders数据
    1.实体类中添加属性
    2.接口中添加方法
    3.mapper实现sql
    4.手动映射关联数据

user类

user与orders是一对多的关系 user中需要一个集合 用来保存orders中的信息
package com.lanou.bean;

import java.util.List;

public class User {
    private int id;
    private String name;
    private String password;
    private String sex;
    private List orders;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public List getOrders() {
        return orders;
    }
    public void setOrders(List orders) {
        this.orders = orders;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", password=" + password + ", sex=" + sex + ", orders=" + orders
                + "]";
    }
}

Orders.java

package com.lanou.bean;

public class Orders {
    private int id;
    private String name;
    private double price;
    private int userid;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public int getUserid() {
        return userid;
    }
    public void setUserid(int userid) {
        this.userid = userid;
    }
    @Override
    public String toString() {
        return "Orders [id=" + id + ", name=" + name + ", price=" + price + ", userid=" + userid + "]";
    }
}

UserDao.java

public interface UserDao {
    // 选择用户及其对应的订单
    public List selectUsersAndOrders();
}

UserDao.xml

"com.lanou.dao.UserDao">

    "User" id="UserMap" autoMapping="true">
        <result property="id" column="u_id"/>
        <result property="name" column="u_name"/>
        property="orders" autoMapping="true" ofType="Orders">
            <result property="name" column="o_name"/>
            <result property="id" column="o_id"/>
        
    


    

MybatisTest.java

public class MybatisTest {
    @Test
    public void test3() throws IOException {
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = builder.build(inputStream);
        SqlSession session = factory.openSession();
        UserDao dao = session.getMapper(UserDao.class);
        List list = dao.selectUsersAndOrders();
        for (User user : list) {
            System.out.println(user);
        }
    }
}

一对一查询

一个员工可以有多张订单 一张订单对应一个员工 从员工角度看 员工与订单是一对多关系
从订单角度看 订单与员工是一对一关系 即一张订单对应一个员工 

实现:获取订单时 自动获取user
创建映射文件 添加方法用来获取所有订单数据

Orders.java

public class Orders {
    private int id;
    private String name;
    private double price;
    private int userid;
    private User user;


    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public int getUserid() {
        return userid;
    }
    public void setUserid(int userid) {
        this.userid = userid;
    }
    @Override
    public String toString() {
        return "Orders [id=" + id + ", name=" + name + ", price=" + price + ", userid=" + userid + ", user=" + user
                + "]";
    }
}

OrderDao.java

public interface OrderDao {
    public List selectAllOrdersAndUser();
}

OrderDao.xml



<mapper namespace="com.lanou.dao.OrderDao">
    <resultMap type="Orders" id="OrdersMap" autoMapping="true">
        <result property="id" column="o_id"/>
        <result property="name" column="o_name"/>
        <association property="user" autoMapping="true" javaType="User">
            <result property="id" column="u_id"/>
            <result property="name" column="u_name"/>
        association>
    resultMap>

    <select id="selectAllOrdersAndUser" resultMap="OrdersMap">
        select *,
        Orders.id as o_id,
        Orders.name as o_name,
        User.id as u_id,
        User.name as u_name
        from Orders left join
        User on Orders.userid = User.id
    select>
mapper>

MybatisTest2.java

public class MybatisTest2 {
    @Test
    public void test3() throws IOException {
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = builder.build(inputStream);
        SqlSession session = factory.openSession();
        OrderDao dao = session.getMapper(OrderDao.class);
        List list = dao.selectAllOrdersAndUser();
        for (Orders orders : list) {
            System.out.println(orders);
        }
    }
}

多对多

现有group和user
  需求 查询user同时查询相关的groups
  需求 查询groups 同时查询相关的user

建立user表 建立groups表 两表之间的联系是一张中间表

Groups.java

package com.lanou.bean;

import java.util.List;

public class Groups {
    private int g_id;
    private String g_name;
    private String g_msg;
    private String g_manager;

    private List users;

    public int getG_id() {
        return g_id;
    }

    public void setG_id(int g_id) {
        this.g_id = g_id;
    }

    public String getG_name() {
        return g_name;
    }

    public void setG_name(String g_name) {
        this.g_name = g_name;
    }

    public String getG_msg() {
        return g_msg;
    }

    public void setG_msg(String g_msg) {
        this.g_msg = g_msg;
    }

    public String getG_manager() {
        return g_manager;
    }

    public void setG_manager(String g_manager) {
        this.g_manager = g_manager;
    }

    public List getUsers() {
        return users;
    }

    public void setUsers(List users) {
        this.users = users;
    }

    @Override
    public String toString() {
        return "groups [g_id=" + g_id + ", g_name=" + g_name + ", g_msg=" + g_msg + ", g_manager=" + g_manager
                + ", users=" + users + "]";
    }
}

User.java

package com.lanou.bean;

import java.util.List;

public class User {
    private int id;
    private String name;
    private String password;
    private String sex;
    private List groups;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public List getGroups() {
        return groups;
    }
    public void setGroups(List groups) {
        this.groups = groups;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", password=" + password + ", sex=" + sex + ", groups=" + groups
                + "]";
    }

}

UserDao.java

public interface UserDao {
    // 选择用户及其对应的群组
    public List selectUsersAndGroups();
}

UserDao.xml




<mapper  namespace="com.lanou.dao.UserDao">

    <resultMap type="User" id="UserMap" autoMapping="true">
        <result property="id" column="id"/>
        <collection property="groups" autoMapping="true" ofType="Groups">
        collection>
    resultMap>
    <select id="selectUsersAndGroups" resultMap="UserMap">
        select *
        from user 
        left join u_r_g on user.id = u_r_g.uid
        left join groups on u_r_g.gid = groups.g_id
    select>
mapper>

MybatisTest3.java

public void test3() throws IOException {
    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
    SqlSessionFactory factory = builder.build(inputStream);
    SqlSession session = factory.openSession();
     UserDao dao = session.getMapper(UserDao.class);
     List user = dao.selectUsersAndGroups();
     for (User user2 : user) {
        System.out.println(user2);
    }
}

Mybatis进阶之表之间的关系_第1张图片

Groups对User

groupsDao.java

public interface groupsDao {
    // 获取所有群组和对应的用户
    public List selectAllGroups();
}

groupsDao.xml



<mapper namespace="com.lanou.dao.groupsDao">
    <resultMap type="Groups" id="GroupsMap" autoMapping="true">
        <result property="id" column="id"/>
        <collection property="users" ofType="User" autoMapping="true">  
        collection>
    resultMap>

    <select id="selectAllGroups" resultMap="GroupsMap">
        select * FROM
        groups left join u_r_g on groups.g_id = u_r_g.gid
        left join user on u_r_g.uid = user.id
    select>
mapper>

MybatisTestnVnTest3.java

public class MybatisTestnVnTest3 {
    @Test
    public void testFun1() throws IOException{
        // 构建器
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        // 读取配置文件
        InputStream input = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 1.获取会话工厂
        SqlSessionFactory factory = builder.build(input);
        // 2.获取会话
        SqlSession session = factory.openSession();
        // 3.crud
        groupsDao mapper = session.getMapper(groupsDao.class);
        List groups = mapper.selectAllGroups();
        for (Groups groups2 : groups) {
            System.out.println(groups2);
        }

    }
}

Mybatis进阶之表之间的关系_第2张图片

你可能感兴趣的:(SSM框架)