MyBatis练习查询所有的一级分类,同时查询二级分类,以及查询二级分类下的所有图书

Posted manor的大数据奋斗之路

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis练习查询所有的一级分类,同时查询二级分类,以及查询二级分类下的所有图书相关的知识,希望对你有一定的参考价值。

一对多

* 查询所有的一级分类,同时查询二级分类,以及查询二级分类下的所有图书

CREATE TABLE category(
  cid VARCHAR(32) PRIMARY KEY,
  cname VARCHAR(50),
  parent_id VARCHAR(32),
  `desc` VARCHAR(100)
);
INSERT INTO category(cid,cname,parent_id,`desc`) VALUES('c100','童书','0','一级分类');
INSERT INTO category(cid,cname,parent_id,`desc`) VALUES('c200','电子书','0','一级分类');

INSERT INTO category(cid,cname,parent_id,`desc`) VALUES('c101','中国儿童文学','c100','二级分类');
INSERT INTO category(cid,cname,parent_id,`desc`) VALUES('c102','婴儿读物','c100','二级分类');

INSERT INTO category(cid,cname,parent_id,`desc`) VALUES('c201','武侠小说','c200','二级分类');
INSERT INTO category(cid,cname,parent_id,`desc`) VALUES('c202','侦探推理','c200','二级分类');


CREATE TABLE book(
  bid VARCHAR(32) PRIMARY KEY,
  title VARCHAR(50),
  price DOUBLE(6,2),
  author VARCHAR(50),
  cid VARCHAR(32)
);

INSERT INTO book(bid,title,price,author,cid) VALUES('b001','学会管自己(歪歪兔独立成长童话)',64.00,'陈梦敏','c101');
INSERT INTO book(bid,title,price,author,cid) VALUES('b002','写给儿童的中国历史',177.50,'陈卫平','c101');

INSERT INTO book(bid,title,price,author,cid) VALUES('b003','小鸡球球触感玩具书',125.00,'[日]入山智','c102');

INSERT INTO book(bid,title,price,author,cid) VALUES('b004','天龙八部',12.00,'金庸','c201');
INSERT INTO book(bid,title,price,author,cid) VALUES('b005','朱贞木短篇小说集(全套装共8册)',103,'朱贞木','c201');
INSERT INTO book(bid,title,price,author,cid) VALUES('b006','笑傲江湖(新修版)一',1200,'金庸','c201');


INSERT INTO book(bid,title,price,author,cid) VALUES('b007','解忧杂货店',19.99,'(日)东野圭吾','c202');
INSERT INTO book(bid,title,price,author,cid) VALUES('b008','三口棺材',8.99,'(美)约翰·迪克森·卡尔','c202');

表结构

核心代码

    /*
    *  查询所有
    * */
    @Select("select * from category c ")
    @Results(value = {
            @Result(property = "cid", column = "cid",id = true),
            @Result(property = "cname", column = "cname"),
            @Result(property = "parent_id", column = "parent_id"),
            @Result(property = "author", column = "author"),
            @Result(property = "desc", column = "desc"),

            @Result(property="categories" , many=@Many(select="com.czxy.mybatis_0929.mapper.CategoryMapper.selectAll2")
                    , column="cid"),
                       @Result(property="books" , many=@Many(select="com.czxy.mybatis_0929.mapper.BookMapper.selectAll")
                    , column="cid"),
    })
    public List<Category> selectAll();
    /*
     *  查询所有
     * */
    @Select("select * from category where cid =#{parent_id}")
    public List<Category> selectAll2(@Param("parent_id")String parent_id);


   /**
     * 查询所有
     * @return
     */
    @Select("select * from book")
    @Results(value = {
            @Result(property = "bid", column = "bid"),
            @Result(property = "title", column = "title"),
            @Result(property = "price", column = "price"),
            @Result(property = "author", column = "author"),
            @Result(property = "cid", column = "cid", id = true),
    })
    public List<Book> selectAll();

运行结果

代码可从Gitee自行下载

https://gitee.com/the_efforts_paid_offf/java.git

参考答案

1.1.1 搭建环境
•项目:day07_mybatis_category_book

1.1.2 JavaBean
•分类Category

 @Entity(name = "category")
public class Category {
    @Id
    private String cid;

    @Column(name = "cname")
    private String cname;

    @Column(name="`desc`")
    private String desc;

    // 父分类id
    @Column(name="parent_id")
    private String parentId;

    //多对一:多个二级分类 对应 一个一级分类
    private Category category;

    //一对多:一个一级分类 对应 多个二级分类
    private List<Category> categoryList = new ArrayList<>();

•书籍Book

 @Entity(name="book")
public class Book {
    @Id
    private String bid;

    @Column(name="title")
    private String title;

    @Column(name="price")
    private Double price;

    @Column(name="author")
    private String author;

    @Column(name="cid")
    private String cid;

    //多对一:多本书 属于 一个分类
    private Category category;

1.1.3 查询所有一级分类
1) 查询指定父分类的所有分类(单表)
•编写功能接口

 package com.czxy.ssm.mapper;

import com.czxy.ssm.domain.Category;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * @author 桐叔
 * @email liangtong@itcast.cn
 */
public interface CategoryMapper {

    /**
     * 查询指定父分类的所有分类
     * @param parentId
     * @return
     */
    public List<Category> selectAll(@Param("parentId") String parentId);
}

•编写SQL语句

 <?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.czxy.ssm.mapper.CategoryMapper">

    <resultMap id="categoryResultMap" type="category">
        <id property="cid" column="cid"></id>
        <result property="cname" column="cname"></result>
        <result property="desc" column="desc"></result>
        <result property="parentId" column="parent_id"></result>
    </resultMap>

    <select id="selectAll" resultMap="categoryResultMap">
        SELECT * FROM category WHERE parent_id = #{parentId}
    </select>

</mapper>

•编程测试类

 package com.czxy.ssm;

import com.czxy.ssm.domain.Category;
import com.czxy.ssm.mapper.CategoryMapper;
import com.czxy.ssm.utils.MyBatisUtils;

import java.util.List;

/**
 * @author 桐叔
 * @email liangtong@itcast.cn
 */
public class Test01_XML_SelectAll {
    public static void main(String[] args) {
        //1 获得mapper
        CategoryMapper categoryMapper = MyBatisUtils.getMapper(CategoryMapper.class);

        //2 查询所有的一级分类,同时查询二级分类,同时查询关联书籍
        List<Category> oneList = categoryMapper.selectAll("0");
        for (Category category : oneList) {
            System.out.println(category);
        }


        //3 释放
        MyBatisUtils.commitAndclose();
    }
}
 

2) 查询指定父分类的所有分类,含二级分类(多表)
•修改JavaBean(已修改)

•修改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.czxy.ssm.mapper.CategoryMapper">

    <resultMap id="categoryResultMap" type="category">
        <id property="cid" column="cid"></id>
        <result property="cname" column="cname"></result>
        <result property="desc" column="desc"></result>
        <result property="parentId" column="parent_id"></result>
        <!--一对多:一个一级分类 对应 多个二级分类-->
        <collection property="categoryList" column="cid" select="com.czxy.ssm.mapper.CategoryMapper.selectAll"></collection>
    </resultMap>

    <select id="selectAll" resultMap="categoryResultMap">
        SELECT * FROM category WHERE parent_id = #{parentId}
    </select>

</mapper>

•修改测试类,方便数据打印

 package com.czxy.ssm;

import com.czxy.ssm.domain.Category;
import com.czxy.ssm.mapper.CategoryMapper;
import com.czxy.ssm.utils.MyBatisUtils;

import java.util.List;

/**
 * @author 桐叔
 * @email liangtong@itcast.cn
 */
public class Test01_XML_SelectAll {
    public static void main(String[] args) {
        //1 获得mapper
        CategoryMapper categoryMapper = MyBatisUtils.getMapper(CategoryMapper.class);

        //2 查询所有的一级分类,同时查询二级分类,同时查询关联书籍
        List<Category> oneList = categoryMapper.selectAll("0");
        // 2.1 打印一级分类
        for (Category oneCategory : oneList) {
            System.out.println("one: " + oneCategory);
            // 2.2 打印二级分类
            for (Category twoCategory : oneCategory.getCategoryList()) {
                System.out.println("two: " + twoCategory);
            }
        }


        //3 释放
        MyBatisUtils.commitAndclose();
    }
}

3)查询指定父分类的所有分类,含二级分类,含书籍信息
•编写BookMapper,功能方法selectAll(cid)

 package com.czxy.ssm.mapper;

import com.czxy.ssm.domain.Book;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * @author 桐叔
 * @email liangtong@itcast.cn
 */
public interface BookMapper {

    /**
     * 查询指定分类id的所有书籍
     * @param categoryId
     * @return
     */
    public List<Book> selectAll(@Param("categoryId") String categoryId);
}

•编写BookMapper.xml ,实现SQL语句

 <?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.czxy.ssm.mapper.BookMapper">

    <select id="selectAll" resultType="book">
        SELECT * FROM book WHERE cid = #{categoryId}
    </select>

</mapper>

•修改Category,提供 List属性
//一对多:一个二级分类 对应 多个书籍
private List bookList = new ArrayList<>();

•修改CategoryMapper.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.czxy.ssm.mapper.CategoryMapper">

    <resultMap id="categoryResultMap" type="category">
        <id property="cid" column="cid"></id>
        <result property="cname" column="cname"></result>
        <result property="desc" column="desc"></result>
        <result property="parentId" column="parent_id"></result>
        <!--一对多:一个一级分类 对应 多个二级分类-->
        <collection property="categoryList" column="cid" select="com.czxy.ssm.mapper.CategoryMapper.selectAll"></collection>

        <!--一对多:一个二级分类 对应 多个书籍 -->
        <collection property="bookList" column="cid" select="com.czxy.ssm.mapper.BookMapper.selectAll"></collection>
    </resultMap>

    <select id="selectAll" resultMap="categoryResultMap">
        SELECT * FROM category WHERE parent_id = #{parentId}
    </select>

</mapper>

•修改测试类,打印书籍信息

 package com.czxy.ssm;

import com.czxy.ssm.domain.Book;
import com.czxy.ssm.domain.Category;
import com.czxy.ssm.mapper.CategoryMapper;
import com.czxy.ssm.utils.MyBatisUtils;

import java.util.List;

/**
 * @author 桐叔
 * @email liangtong@itcast.cn
 */
public class Test01_XML_SelectAll {
    public static void main(String[] args) {
        //1 获得mapper
        CategoryMapper categoryMapper = MyBatisUtils.getMapper(CategoryMapper.class);

        //2 查询所有的一级分类,同时查询二级分类,同时查询关联书籍
        List<Category> oneList = categoryMapper.selectAll("0"Mybatis练习(一对多:查询所有的一级分类,同时查询二级分类,以及查询二级分类下的所有图书)

MyBatis中的一级缓存和二级缓存介绍

课时10:MyBatis一级缓存二级缓存

Mybatis一级缓存和二级缓存总结

mybatis一级缓存和二级缓存

MyBatis一级缓存和二级缓存