【作业题】通过MyBatis查询文章信息及关联的评论信息

模块作业思路

1. 编程题

作业地址:https://gitee.com/robin_p_liu/stage-6.git

1.1 需求:查询文章信息及关联的评论信息
1.2 要求:
1. 整体实现要基于XML配置方式

2. 文章和评论是一对多关系,在查询文章信息及关联的评论信息时,需实现延迟加载效果
1.3 SQL资源:

文章-评论:一对多,评论表的外键指向文章表的主键

	# 创建数据库
	CREATE DATABASE springbootdata;
	# 选择使用数据库
 	USE springbootdata;
	# 创建表t_article并插入相关数据
	DROP TABLE IF EXISTS t_article;
 	CREATE TABLE t_article (
	  id int(20) NOT NULL AUTO_INCREMENT COMMENT '文章id',
	  title varchar(200) DEFAULT NULL COMMENT '文章标题',
 	  content longtext COMMENT '文章内容',
 	  PRIMARY KEY (id)
 	) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
	INSERT INTO t_article VALUES ('1', 'Spring Boot基础入门', '从入门到精通讲解...');
	INSERT INTO t_article VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲解...');
 	# 创建表t_comment并插入相关数据
	DROP TABLE IF EXISTS t_comment;
	CREATE TABLE t_comment (
	  id int(20) NOT NULL AUTO_INCREMENT COMMENT '评论id',
 	  content longtext COMMENT '评论内容',
	  author varchar(200) DEFAULT NULL COMMENT '评论作者',
	  a_id int(20) DEFAULT NULL COMMENT '关联的文章id',
	  PRIMARY KEY (id)
	) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
	INSERT INTO t_comment VALUES ('1', '很全、很详细', 'lucy', '1');
	INSERT INTO t_comment VALUES ('2', '赞一个', 'tom', '1');
	INSERT INTO t_comment VALUES ('3', '很详细', 'eric', '1');
	INSERT INTO t_comment VALUES ('4', '很好,非常详细', '张三', '1');
	INSERT INTO t_comment VALUES ('5', '很不错', '李四', '2');

2. 打开SQLyog创建数据库、表

在这里插入图片描述

3. 打开IDEA创建maven工程

在这里插入图片描述

3.1 基础配置
3.1.1 pom.xml
<!--指定编码及版本-->
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
    <java.version>1.11</java.version>
    <maven.compiler.source>1.11</maven.compiler.source>
    <maven.compiler.target>1.11</maven.compiler.target>
</properties>

<!--引入相关依赖-->
<dependencies>
    <!--引入mybatis依赖-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.4</version>
    </dependency>

    <!--引入mysql驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>

    <!--引入junit-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>

</dependencies>
3.1.2 jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///springbootdata?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=******
3.2 编写实体类
public class Article {
    private int id;
    private String title;
    private String content;
    // getter/setter 略
    
    // 代表当前文章所具有的评论 collection
    private List<Comment> commentsList;
    // 重写toString方法 打印commentsList
}
public class Comment {
    private int id;
    private String content;
    private String author;
    private int aid;
    // getter/setter 略
}
3.3 分析需求
3.3.1 编写sql语句

需求:查询文章信息及关联的评论信息

一对多 联合查询

SELECT * FROM t_article a LEFT JOIN t_comment c ON a.id = c.a_id;

一对多 嵌套查询

-- 先查询文章
SELECT * FROM t_article;
-- 再根据文章id主键,查询评论信息列表
SELECT * FROM t_comment where a_id = #{文章id};
3.3.2 在实体类添加对应信息

见3.2

3.3.3 编写ArticleMapper接口
public interface ArticleMapper {
    public List<Article> findAllWithComment();
}
3.3.4 编写CommentMapper接口
public interface CommentMapper {
    public List<Comment> findByAid(Integer aid);
}
3.3 编写映射配置文件
3.3.1 ArticleMapper.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="mapper.ArticleMapper">
    <!--一对多嵌套查询-->
    <resultMap id="articleMap" type="Article">
        <id column="id" property="id"></id> <!--主键-->
        <result column="title" property="title"></result>
        <result column="content" property="content"></result>
        <!--根据文章id主键,查询评论信息列表-->
        <!--
            一对多使用collection标签关联
            property="commentsList" 封装到Article.java中集合的属性名
            ofType="Comment" 封装集合的泛型类型
        -->
        <collection column="id" property="commentsList" ofType="Comment"
                    select="mapper.CommentMapper.findByAid"></collection>
    </resultMap>

    <select id="findAllWithComment" resultMap="articleMap">
        SELECT * FROM t_article
    </select>
</mapper>
3.3.2 CommentMapper.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="mapper.CommentMapper">
    <select id="findByAid" parameterType="int" resultType="Comment">
        SELECT * FROM t_comment where a_id = #{aid}
    </select>
</mapper>
3.4 编写核心配置文件

SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <!--加载properties文件-->
    <properties resource="jdbc.properties"></properties>

    <settings>
    <!--开启全局延迟加载功能-->
    <setting name="lazyLoadingEnabled" value="true"/>
    <!--equals、clone、hashCode、toString方法都会延迟加载-->
    <setting name="lazyLoadTriggerMethods" value="toString()"/>
    </settings>

    <!--设置别名-->
    <typeAliases>
        <!--批量起别名 别名就是类名,且不区分大小写-->
        <package name="domain"/>
    </typeAliases>

    <!--environments: 运行环境-->
    <environments default="development">
        <environment id="development">
            <!--当前的事务事务管理器是JDBC-->
            <transactionManager type="JDBC"></transactionManager>
            <!--数据源信息 POOLED:使用mybatis的连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--引入映射配置文件-->
    <mappers>
        <!--批量加载映射-->
        <package name="mapper"/>
    </mappers>

</configuration>
3.5 编写测试类
public class MybatisTest {

    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;


    // 在 @Test方法标注的方法执行之前来执行
    @Before
    public void before() throws IOException {
        //1.加载核心配置文件
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        //2. 获取sqlSessionFactory工厂对象
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        //3. 获取sqlSession会话对象
        sqlSession = sqlSessionFactory.openSession();
    }


    @After
    public void after() {
        sqlSession.commit();
        sqlSession.close();

    }

    /*
       一对多嵌套查询:查询文章信息及关联的评论信息
   */
    @Test
    public void testArticleWithComment() {
        ArticleMapper articleMapper = sqlSession.getMapper(ArticleMapper.class);

        List<Article> allWithComment = articleMapper.findAllWithComment();

        for (Article article : allWithComment) {
            // 获取文章信息
            System.out.println(article);

            // 延迟加载:获取文章对应评论信息
            System.out.println(article.getCommentsList());
        }
    }
}
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值