序
准备工作:
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表如下:
运行测试类代码,结果如下: