本文主要是介绍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 taleft join userinfo tbon ta.uid = tb.idwhere 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 {@Autowiredprivate ArticleInfoMapper articleInfoMapper;@Testvoid selectArticleAndUserById() {System.out.println(articleInfoMapper.selectArticleAndUserById(1));}
}
articleInfo和userinfo表如下:
运行测试类代码,结果如下:
这篇关于Mybatis--其他查询操作和数据库连接池(下下)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!