java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > mybatis多表查询

mybatis于xml方式和注解方式实现多表查询的操作方法

作者:忆梦~留念

在数据库中,单表的操作是最简单的,但是在实际业务中最少也有十几张表,并且表与表之间常常相互间联系,本文给大家介绍mybatis于xml方式和注解方式实现多表查询的操作方法,感兴趣的朋友一起看看吧

推荐阅读

https://www.jb51.net/article/253091.htm

1、解释

在数据库中,单表的操作是最简单的,但是在实际业务中最少也有十几张表,并且表与表之间常常相互间联系;

一对一、一对多、多对多是表与表之间的常见的关系。

2、操作

1、数据库中创建表格brand,并插入数据

DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(11) COLLATE utf8mb4_general_ci NOT NULL,
  `money` decimal(10,2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
-- ----------------------------
-- Records of account
-- ----------------------------
INSERT INTO `account` VALUES ('1', 'messi', '1000.00');
INSERT INTO `account` VALUES ('2', 'pep', '1000.00');
select `position`,count(`position`) amount from users group by `position`
select p.product_name productName,sum(p_r.quantity) prquantity,sum(s_r.quantity) srquantity from products p left join purchase_records p_r on p.product_id=p_r.product_id left join sales_records s_r on p.product_id=s_r.product_id where p.state=1 group by p.product_id 
order by srquantity desc limit 0,5;
DROP TABLE IF EXISTS `brand`;
CREATE TABLE `brand` (
  `brand_id` int NOT NULL AUTO_INCREMENT COMMENT '品牌编号',
  `brand_name` varchar(255) COLLATE utf8mb4_general_ci NOT NULL COMMENT '品牌名称',
  `company_name` varchar(255) COLLATE utf8mb4_general_ci NOT NULL COMMENT '所属公司名称',
  `brand_idea` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '品牌理念',
  PRIMARY KEY (`brand_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
-- ----------------------------
-- Records of brand
-- ----------------------------
INSERT INTO `brand` VALUES ('1', '华为手机', '华为技术有限公司', 'Make It Possible');
INSERT INTO `brand` VALUES ('2', '荣耀', '深圳市智信新信息技术有限公司', 'GO BEYOND');
INSERT INTO `brand` VALUES ('3', '红米', '小米科技有限责任公司', '不顾一切的热爱');

2、com.entity中创建实体类Brand  

 
@Data
public class Brand {
    //品牌编号
    private Integer brandId;
    //品牌名称
    private String brandName;
    //品牌所属公司
    private String companyName;
    //品牌理念
    private String brandIdea;
    //旗下手机列表
    private List<String> phoneList;
}

3、com.entity中修改实体类Phone

@Data
public class Phone {
//    手机编号
    private Integer phoneId;
//    品牌编号
//    private Integer brandId;
    //手机品牌
    private Brand brand;
//    手机型号
    private String modelNumber;
//    手机容量
    private Integer capacity;
}

4、实现查询手机信息及其所属品牌信息

xml方式:修改方法selectAll对应的xml

写法一:

<resultMap id="phoneMap" type="phone">
        <id column="phone_id" property="phoneId"></id>
        <id column="model_number" property="modelNumber"></id>
        <id column="capacity" property="capacity"></id>
        <id column="brand_id" property="brand.brandId"></id>
        <id column="brand_name" property="brand.brandName"></id>
        <id column="company_name" property="brand.companyName"></id>
        <id column="brand_idea" property="brand.brandIdea"></id>
    </resultMap>
    <select id="selectAll" resultMap="phoneMap">
        SELECT * FROM phone p,brand b
        where p.brand_id = b.brand_id
    </select>

写法二:

<resultMap id="phoneMap" type="phone">
                <id column="phone_id" property="phoneId"></id>
                <id column="model_number" property="modelNumber"></id>
                <id column="capacity" property="capacity"></id>
        <!--        property:当前实体(Hero)中的属性名称(private Hero hero)-->
        <!--        javaType:当前实体(Hero)中的属性类型(com.cqgcxy.entity.Hero)-->
        <association property="brand" javaType="com.cqgcxy.entity.Brand">
            <id column="brand_id" property="brandId"></id>
            <id column="brand_name" property="brandName"></id>
            <id column="company_name" property="companyName"></id>
            <id column="brand_idea" property="brandIdea"></id>
        </association>
    </resultMap>
    <select id="selectAll" resultMap="phoneMap">
        SELECT * FROM phone p,brand b
        where p.brand_id = b.brand_id
    </select>

注解方式:  

注意:注解方式的mapper配置可以不用在配置mapper文件地址,而是只配置包的路径。

写法一:修改PhoneMapper接口中selectAll方法

@Select("SELECT * FROM phone p,brand b where p.brand_id = b.brand_id")
    @Results({
            @Result(column = "phone_id",property = "phoneId"),
            @Result(column = "model_number",property = "modelNumber"),
            @Result(column = "capacity",property = "capacity"),
            @Result(column = "brand_id",property = "brand.brandId"),
            @Result(column = "brand_name",property = "brand.brandName"),
            @Result(column = "company_name",property = "brand.companyName"),
            @Result(column = "brand_idea",property = "brand.brandIdea")
    })
    List<Phone> selectAll();

写法二:

创建并编写BrandMapper接口

public interface BrandMapper {
    @Select("SELECT * FROM brand WHERE brand_id = #{brandId}")
    Brand selectById(Long brandId);
}

修改PhoneMapper接口中selectAll方法

@Select("SELECT * FROM phone")
@Results({
        @Result(column = "phone_id",property = "phoneId"),
        @Result(column = "model_number",property = "modelNumber"),
        @Result(column = "capacity",property = "capacity"),
        @Result(column = "brand_id",
                property = "brand",
                javaType = Brand.class,
                one = @One(select="com.dao.BrandMapper.selectById")
        )
})
List<Phone> selectAll();

调用测试类中MybatisMapperTest中selectAllTest方法测试  

5、实现查询品牌信息及其旗下的手机信息

BrandMapper接口中添加抽象方法selectAll

List<Brand> selectAll();

xml方式:mapper文件夹中创建BrandMapper.xml并编写selectAll方法对应的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.dao.BrandMapper">
    <resultMap id="brandMap" type="com.entity.Brand">
        <id column="brand_id" property="brandId"></id>
        <result column="brand_name" property="brandName"></result>
        <result column="company_name" property="companyName"></result>
        <result column="brand_idea" property="brandIdea"></result>
        <collection property="phoneList" ofType="com.entity.Phone">
            <result column="phone_id" property="phoneId"></result>
            <result column="model_number" property="modelNumber"></result>
            <result column="capacity" property="capacity"></result>
        </collection>
    </resultMap>
    <select id="selectAll" resultMap="brandMap">
        SELECT * FROM brand b LEFT JOIN phone p
                                        ON p.brand_id=b.brand_id
    </select>
</mapper>

测试

public class BrandMapperTest {
    @Test
    public void selectAll() throws IOException {
        InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqLSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlsession = sqLSessionFactory.openSession();
        BrandMapper brandMapper = sqlsession.getMapper(BrandMapper.class);
        List<Brand> brands = brandMapper.selectAll();
        brands.forEach(s->{
            System.out.println(s);
        });
        sqlsession.close();
    }
}

 为了方便可以

注解方式:

修改PhoneMapper接口中添加selectByBrandId方法

@Select("SELECT * FROM phone WHERE brand_id = #{brandId}")
    Phone selectByBrandId(Integer brandId);

修改BrandMapper接口中selectAll方法  

    @Select("SELECT * FROM brand")
    @Results({
            @Result(column = "brand_id",property = "brandId"),
            @Result(column = "brand_name",property = "brandName"),
            @Result(column = "company_name",property = "companyName"),
            @Result(column = "brand_idea",property = "brandIdea"),
            @Result(column = "brand_id",
                    property = "phoneList",
                    javaType = List.class,
                    many = @Many(select = "com.dao.PhoneMapper.selectByBrandId")
            )
    })
    List<Brand> selectAll();

运行出现

Mybatis注解方式:

@lnsert:实现新增

@Update:实现更新

@Delete:实现删除

@Select:实现查询

@Result:实现结果集封装

@Results:可以与@Result一起使用,封装多个结果集

@One:实现一对一结果集封装

@Many:实现一对多结果集封装

到此这篇关于mybatis基于xml方式和注解方式实现多表查询的文章就介绍到这了,更多相关mybatis多表查询内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文