Mybatis--其他查询操作和数据库连接池(下下)

        准备工作:

mysql数据库和表的信息更新:

DROP TABLE IF EXISTS articleinfo;

CREATE TABLE articleinfo (
                             id INT PRIMARY KEY auto_increment,
                             title VARCHAR ( 100 ) NOT NULL,
                             content TEXT NOT NULL,
                             uid INT NOT NULL,
                             delete_flag TINYINT ( 4 ) DEFAULT 0 COMMENT '0-正常, 1-删除',
                             create_time DATETIME DEFAULT now(),
                             update_time DATETIME DEFAULT now()
) DEFAULT charset 'utf8mb4';

-- 插入测试数据
INSERT INTO articleinfo ( title, content, uid ) VALUES ( '十日游戏', 'snh48群像', 1 );

对应实体类model:

package com.example.zxslzw_mybaties.model;

import lombok.Data;

import java.util.Date;

@Data
public class ArticleInfo {
    private Integer id;
    private String title;
    private String content;
    private Integer uid;
    private Integer deleteFlag;;
    private Date createTime;
    private Date updateTime;
    //用户相关的信息
    private String username;
    private Integer gender;
}

1. 多表查询

        多表查询和单表查询差不多,只是SQL代码不同,下面是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.example.zxslzw_mybaties.mapper.ArticleInfoMapper">
    <select id="selectArticleAndUserById" resultType="com.example.zxslzw_mybaties.model.ArticleInfo">
        select ta.*, tb.username, tb.gender from articleinfo ta
        left join userinfo tb
        on ta.uid = tb.id
        where ta.id = #{id}
    </select>
</mapper>

 ArticleInfoMapper接口代码如下:

package com.example.zxslzw_mybaties.mapper;

import com.example.zxslzw_mybaties.model.ArticleInfo;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface ArticleInfoMapper {
    List<ArticleInfo> selectArticleAndUserById(Integer id);
}

 测试类代码如下:

package com.example.zxslzw_mybaties.mapper;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class ArticleInfoMapperTest {
    @Autowired
    private ArticleInfoMapper articleInfoMapper;

    @Test
    void selectArticleAndUserById() {
        System.out.println(articleInfoMapper.selectArticleAndUserById(1));
    }
}

 articleInfo和userinfo表如下:

 运行测试类代码,结果如下:

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值