[Mybatis 一对多 多对多 ] 待更新

14 篇文章 0 订阅

目录

前言:

项目结构:

myuser类:

post类:

启动类:

controller:

mapper接口

Mapper.xml

数据库表结构:

一对多返回格式? (这里主要为 一个用户拥有多个文章):


前言:

就是无聊记录一下…

项目结构:

myuser类:

@Data
public class MyUser {

private int id;
private String username;
private String mobile;
private List<Post> posts;

}

post类:

@Data
public class Post {

private int id;
private Integer userid;
private String title;
private String content;

}

启动类:

@SpringBootApplication
@MapperScan(“com.luo.mybatisdemo.dao”)
public class MybatisdemoApplication {

public static void main(String\[\] args) {
    SpringApplication.run(MybatisdemoApplication.class, args);
}

}

controller:

@RequestMapping("/hello1")
public List hello1(){
List books = myUserMapper.getAllBooks(1);
return books;
}

mapper接口

List getAllBooks(Integer id);

Mapper.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.luo.mybatisdemo.dao.MyUserMapper">
    <!-- User 级联文章查询 方法配置 (一个用户对多个文章)  -->

    <resultMap type="com.luo.mybatisdemo.entity.MyUser" id="resultUserMap">
        <result property="id" column="id" />
        <result property="username" column="username" />
        <result property="mobile" column="mobile" />
        <collection property="posts" ofType="com.luo.mybatisdemo.entity.Post" >
            <id property="id" column="post_id" />
            <result property="title" column="title" />
            <result property="content" column="content"  />
            <result property="userid" column="userid"  />

        </collection>
    </resultMap>

    <select id="getAllBooks" resultMap="resultUserMap">
		SELECT u.*,p.*
		FROM myuser u, post p
		WHERE u.id=p.userid AND u.id=#{user_id}
  </select>

</mapper>

数据库表结构:

post表:

myuser表:

一对多返回格式 (这里主要为 一个用户拥有多个文章):

[{
“id”: 1,
“username”: “yiibai”,
“mobile”: “100”,
“posts”: [{
“id”: 1,
“userid”: 1,
“title”: “MyBatis关联数据查询”,
“content”: “在实际项目中,经常使用关联表的查询,比如:多对一,一对多等。这些查询是如何处理的呢,这一讲就讲这个问题。我们首先创建一个 post 表,并初始化数据.”
}, {
“id”: 2,
“userid”: 1,
“title”: “MyBatis开发环境搭建”,
“content”: “为了方便学习,这里直接建立java 工程,但一般都是开发 Web 项目。”
}]
}]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值