前面步骤

http://t.csdnimg.cn/IPXMY

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:实现一对多结果集封装

 

原文地址:https://blog.csdn.net/qq_67832732/article/details/134637793

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_10369.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注