mabatis基于xml方式和注解方式实现多表查询

前面步骤

http://t.csdnimg.cn/IPXMY

1、解释

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

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

  • 一对一:一张表A中的一条记录只能对应另一张表B中的一条记录另一张表B中的一条记录也只能对应一张表A中的一条记录。如:一个学生只能对应一张学生卡,一张学生卡只能对应一个学生,那么学生和学生卡就是一对一的关系;

  • 一对多:一张表A中的一条记录可以对应另一张表B中的多条记录另一张表B中的一条记录只能对应一张表A中的一条记录。如:一个班级对应多个学生,一个学生只能对应一个班级,所以班级表中的一条记录可以对应学生表的多条数据,学生表中的一条记录只能对应班级表的一条数据;

  • 多对多的意思是:一张表A中的一条记录可以对应另一张表B中的多条记录,另一张表B中的一条记录也可以对应一张表A中的多条记录。如:一个学生对应多个课程,一个课程对应多个学生。多对多需要设计三张表。比如这里出来学生表和课程表,还需要一张学生课程关联表。学生和课程的关系就存在课程表中。

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 phoneList;
}

mabatis基于xml方式和注解方式实现多表查询_第1张图片

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

mabatis基于xml方式和注解方式实现多表查询_第2张图片

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

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

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

写法一:


        
        
        
        
        
        
        
    
    

 mabatis基于xml方式和注解方式实现多表查询_第3张图片

写法二:


                
                
                
        
        
        
            
            
            
            
        
    
    

注解方式:  

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

mabatis基于xml方式和注解方式实现多表查询_第4张图片

写法一:修改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 selectAll();

mabatis基于xml方式和注解方式实现多表查询_第5张图片

写法二:

创建并编写BrandMapper接口

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

mabatis基于xml方式和注解方式实现多表查询_第6张图片

修改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 selectAll();

 mabatis基于xml方式和注解方式实现多表查询_第7张图片

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

mabatis基于xml方式和注解方式实现多表查询_第8张图片

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

BrandMapper接口中添加抽象方法selectAll

List selectAll();

mabatis基于xml方式和注解方式实现多表查询_第9张图片

xml方式:mapper文件夹中创建BrandMapper.xml并编写selectAll方法对应的sql




    
        
        
        
        
        
            
            
            
        
    
    

mabatis基于xml方式和注解方式实现多表查询_第10张图片

测试

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 brands = brandMapper.selectAll();
        brands.forEach(s->{
            System.out.println(s);
        });
        sqlsession.close();
    }
}

 为了方便可以

mabatis基于xml方式和注解方式实现多表查询_第11张图片

注解方式:

修改PhoneMapper接口中添加selectByBrandId方法

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

mabatis基于xml方式和注解方式实现多表查询_第12张图片

修改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 selectAll();

mabatis基于xml方式和注解方式实现多表查询_第13张图片

运行出现

mabatis基于xml方式和注解方式实现多表查询_第14张图片

mabatis基于xml方式和注解方式实现多表查询_第15张图片 mabatis基于xml方式和注解方式实现多表查询_第16张图片

Mybatis注解方式:

@lnsert:实现新增

@Update:实现更新

@Delete:实现删除

@Select:实现查询

@Result:实现结果集封装

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

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

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

 

你可能感兴趣的:(java,xml,mybatis,spring)