ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-05-30 13:02:35  阅读:170  来源: 互联网

标签:comment 信息 public 作业题 private 文章 MyBatis article id


模块作业思路

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());
        }
    }
}

标签:comment,信息,public,作业题,private,文章,MyBatis,article,id
来源: https://blog.csdn.net/weixin_45883310/article/details/117396823

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有