Mybatis的多表操作与注解开发_mybatis 注解 多表 joiner-程序员宅基地

技术标签: spring  java  mybatis  intellij-idea  

一、Mybatis多表操作

1.一对一查询

        比如有一个用户表和一个订单表,一个用户有多个订单,但一个订单只从属于一个用户,这时查询一个订单,与此同时查询出该订单所属的用户就为一对一查询。

 

①.创建order与user实体

public class Order {
    private int id;
    private Date ordertime;
    private double total;

    //当前订单属于哪一个用户
    private User user;
}

public class User {
    private int id;
    private String username;
    private String password;
    private Date birthday;
}

②.创建OrderMapper接口

public interface OrderMapper {
    public List<Order> findAll();
}

③.配置OrderMapper.xml

<mapper namespace="xx.xx.xxx.OrderMapper">
    <resultMap id="orderMap" type="xx.xx.xxx.Order">
        <result column="uid" property="user.id"></result>
        <result column="username" property="user.username"></result>
        <result column="password" property="user.password"></result>
        <result column="birthday" property="user.birthday"></result>
    </resultMap>
    <select id="findAll" resultMap="orderMap">
        select * from orders o,user u where o.uid=u.id
    </select>
</mapper>

<resultMap id="orderMap" type="xx.xx.xxx.Order">
    <result property="id" column="id"></result>
    <result property="ordertime" column="ordertime"></result>
    <result property="total" column="total"></result>
    <association property="user" javaType="com.itheima.domain.User">
        <result column="uid" property="id"></result>
        <result column="username" property="username"></result>
        <result column="password" property="password"></result>
        <result column="birthday" property="birthday"></result>
    </association>
</resultMap

④.测试

@Test
public void test() throws IOException {
    InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    
    OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
    List<Order> orderList = mapper.findAll();
    for (Order order : orderList) {
        System.out.println(order);
    }
    sqlSession.close();
}

2.一对多查询

        一个用户可以有多个订单,所以查询一个用户,同时查询出该用户具有的订单就是一对多查询。

①.更新user实体

//描述的是当前用户存在哪些订单
private List<Order> orderList;

②.创建usermapper接口

public interface UserMapper {
    public List<User> findAll();
}

③.配置UserMapper.xml

<resultMap id="userMap" type="user">
    <id column="uid" property="id"></id>
    <result column="username" property="username"></result>
    <result column="password" property="password"></result>
    <result column="birthday" property="birthday"></result>
    <!--配置集合信息
        property:集合名称
        ofType:当前集合中的数据类型
    -->
    <collection property="orderList" ofType="order">
        <!--封装order的数据-->
        <id column="oid" property="id"></id>
        <result column="ordertime" property="ordertime"></result>
        <result column="total" property="total"></result>
    </collection>
</resultMap>

<select id="findAll" resultMap="userMap">
    SELECT *,o.id oid FROM USER u,orders o WHERE u.id=o.uid
</select>

④.测试

@Test
public void test2() throws IOException {
    InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> userList = mapper.findAll();
    for(User user : userList){
        System.out.println(user.getUsername());
        List<Order> orderList = user.getOrderList();
        for(Order order : orderList){
            System.out.println(order);
        }
        System.out.println("----------------------------------");
    }
    sqlSession.close();
}

3.多对多查询

        如一个用户有多个角色,一个角色被多个用户使用。

public class Role {
    private int id;
    private String roleName;
    private String roleDesc;
}

①.更新user

//描述的是当前用户具备哪些角色
private List<Role> roleList;

②.在usermapper接口添加方法

List<User> findAllUserAndRole();

③.配置UserMapper.xml

<resultMap id="userRoleMap" type="user">
    <!--user的信息-->
    <id column="userId" property="id"></id>
    <result column="username" property="username"></result>
    <result column="password" property="password"></result>
    <result column="birthday" property="birthday"></result>
    <!--user内部的roleList信息-->
    <collection property="roleList" ofType="role">
        <id column="roleId" property="id"></id>
        <result column="roleName" property="roleName"></result>
        <result column="roleDesc" property="roleDesc"></result>
    </collection>
</resultMap>

<select id="findUserAndRoleAll" resultMap="userRoleMap">
    SELECT * FROM USER u,sys_user_role ur,sys_role r WHERE u.id=ur.userId AND ur.roleId=r.id
</select>

④.测试

@Test
public void test3() throws IOException {
    InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> userAndRoleAll = mapper.findUserAndRoleAll();
    for(User user : userAndRoleAll){
        System.out.println(user.getUsername());
        List<Role> roleList = user.getRoleList();
        for(Role role : roleList){
            System.out.println(role);
        }
        System.out.println("----------------------------------");
    }
    sqlSession.close();
}

二、Mybatis注解开发

1.常用注解

@Insert:实现新增                                    @Update:实现更新

@Delete:实现删除                                   @Select:实现查询

@Result:实现结果集封装                        @Results:可以与@Result 一起使用,封装多个结果集

@One:实现一对一结果集封装                 @Many:实现一对多结果集封装

2.注解配置Mapper例子

public interface OrderMapper {

    @Select("select * from orders where uid=#{uid}")
    public List<Order> findByUid(int uid);

    @Select("select * from orders")
    @Results({
            @Result(column = "id",property = "id"),
            @Result(column = "ordertime",property = "ordertime"),
            @Result(column = "total",property = "total"),
            @Result(
                    property = "user", //要封装的属性名称
                    column = "uid", //根据那个字段去查询user表的数据
                    javaType = User.class, //要封装的实体类型
                    //select属性 代表查询那个接口的方法获得数据
                    one = @One(select = "com.itheima.mapper.UserMapper.findById")
            )
    })
    List<Order> findAll();
}
@Test
public void testSelectOrderAndUser() {
    List<Order> all = orderMapper.findAll();
    for(Order order : all){
        System.out.println(order);
    }
}

 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/xghdxdb/article/details/122068180

智能推荐

动态更新阿里云DDNS解析记录的IPv6地址,随时随地用域名远程访问自己的电脑【如何远程访问家里的电脑】_阿里云ipv6动态域名解析-程序员宅基地

文章浏览阅读1.3w次,点赞15次,收藏85次。本文详细描述了如何利用IPv6+域名解析实现远程访问自己的电脑_阿里云ipv6动态域名解析

使用 Swift iOS 15+ 将经过微调的人工智能与 OpenAI 集成和利用:聊天机器人教程_ios 集成openai-程序员宅基地

文章浏览阅读540次。欢迎来到使用强大的编程语言 Swift 以及 UIKit 框架和 OpenAI 令人难以置信的 Davinci 人工智能模型训练您自己的聊天机器人模型的激动人心的旅程。在这个循序渐进的教程中,我们将深入 AI 和应用程序开发的世界,结合尖端技术来训练能够进行有意义对话的聊天机器人模型。想象一下,拥有一个可以理解和响应自然语言的聊天机器人模型,为用户提供个性化和智能的交互。借助 Swift 和 Davinci 模型,我们拥有实现这一目标的完美工具。_ios 集成openai

CentOS安装MySQL8详细步骤-程序员宅基地

文章浏览阅读2w次,点赞10次,收藏70次。MySQL8安装详细步骤_centos安装mysql8

【Struts2】实现用户登录与登录验证简单示例_struts2登录验证-程序员宅基地

文章浏览阅读1.4k次。一、Struts2相关文件配置1.导入jar包:2.配置web.xml文件:<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> &_struts2登录验证

安卓蓝牙问题一般分析步骤_bluetoothphonepolicy-程序员宅基地

文章浏览阅读3.4k次,点赞2次,收藏26次。BT问题解决步骤确认问题:需要分清模块(Audio,BT,Power等)声音类问题的大部分是Audio模块的;功耗类问题,优先要求功耗的负责人先进行分析;本地复现:(必现或高概率问题一定要本地复现下)确认复现步骤,排除测试步骤问题(误操作或测试用例不对);对比验证:(必现或高概率问题,最好本地对比验证下)更换对比机,同类型三方apk,车载设备,连接设备;Check Log:需要check测试提供的有效性分析问题以APLog和HCILog为主,log时间点和问题复现需要对应,log_bluetoothphonepolicy

pip异常解决办法 Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/usr_gym could not install packages due to an environme-程序员宅基地

文章浏览阅读3.4k次。使用 pip install gym 命令出现以下错误:##Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: ‘/usr/local/lib/python2.7/dist-packages/_markupbase’Consider using the --user optio..._gym could not install packages due to an environmenterror:

随便推点

全局变量和局部变量_说明局部变量在哪个文件中声明,在哪个文件中给全局变量中赋初值,并举例说明一个全-程序员宅基地

文章浏览阅读1.6k次。C语言_说明局部变量在哪个文件中声明,在哪个文件中给全局变量中赋初值,并举例说明一个全

【20090603-02】地图投影的选择(转载)http://blog.csdn.net/chenyq2008/archive/2007/12/04/1915918.aspx...-程序员宅基地

文章浏览阅读92次。地图投影的选择选择投影的目的在于使所选投影的性质、特点适合于地图的用途,同时考虑地图在图廓范围内变形较小而且变形分布均匀。海域使用的地图多采用保角投影,因其能保持方位角度的正确。我国的基本比例尺地形图(1:5千,1:1万,1:2.5万,1:5万,1:10万,1:25万,1:50万,1:100万)中,大于等于50万的均采用高斯-克吕格投影(Gauss-Kruger),这是一个等角横切椭圆柱投影,..._墨卡托投影标准纬线之前长度缩小,标准纬线之外长度放大

微生物分子生态学研究方法培训通知(禇海燕/冯友智/陈瑞蕊/蔡元锋/叶茂等)-程序员宅基地

文章浏览阅读1.0k次。各有关单位:为进一步提高并推动高等院校、科研院所及企事业单位在生态环境科学研究中的技术应用水平。“农环视界”公众号组织邀请本领域知名专家定期举办“生态环境科学研究先进技术培训”。通过课程培训提高学科实验、实践技术应用水平并掌握相关先进技术方法。老师讲课会结合实际案例进行内容解析,并配备实操单元进行针对性指导,解决实际问题,拓宽学员的理论知识、提升学员的实际操作能力及相关经验。本期主题:微生物分子..._禇海燕二级教授

linus开启snmp_Linux配置snmp-程序员宅基地

文章浏览阅读264次。机器环境[root@linux-node1 ~]# cat /etc/redhat-releaseCentOS Linux release 7.1.1503 (Core)[root@linux-node1 ~]# hostnamelinux-node1.nmap.com[root@linux-node1 ~]#安装net-snmp等工具[root@linux-node1 ~]# yum insta..._net-snmp-utils-5.7.2-24.el7_2.1x86

使用Hammerspoon打造你的个性化 macOS 桌面:一个强大的自动化工具-程序员宅基地

文章浏览阅读346次,点赞3次,收藏5次。使用Hammerspoon打造你的个性化 macOS 桌面:一个强大的自动化工具项目地址:https://gitcode.com/zuorn/hammerspoon_configHammerspoon 是一款针对macOS的强大扩展工具,它允许用户通过 Lua 脚本来控制和定制操作系统的行为。这个项目提供了一个预配置的 Hammerspoon 配置集合,旨在帮助新手快速上手并体验到 Hamme..._macos 桌面程序自动化

Web逆向、软件逆向、安卓逆向、APP逆向,关于网络安全这些你必须懂_网络安全逆向-程序员宅基地

文章浏览阅读906次,点赞21次,收藏11次。为了帮助大家更好的学习网络安全,小编给大家准备了一份网络安全入门/进阶学习资料,里面的内容都是适合零基础小白的笔记和资料,不懂编程也能听懂、看懂,所有资料共282G,朋友们如果有需要全套网络安全入门+进阶学习资源包,可以点击免费领取(如遇扫码问题,可以在评论区留言领取哦)~有需要的小伙伴,可以点击下方链接免费领取或者V扫描下方二维码免费领取CSDN大礼包:全网最全《网络安全入门&进阶学习资源包》免费分享**(安全链接,放心点击)**​。