Jpa连接查询之一对多查询

使用原因:

已有商品表,在处理商品属性关系时,是多对多关系,为不影响商品管理,新建商品属性表product_specs和属性表specs。

使用方法:

需对关联表product_specs 表设置外键,获取商品属性:

    @ManyToOne(cascade={CascadeType.MERGE,CascadeType.REFRESH},optional=false)//可选属性optional=false,表示product不能为空。删除文章,不影响用户
    @JoinColumn(name="product_id")//设置在product表中的关联字段(外键)
    private Product product;//关联商品外键
    @ManyToOne(cascade = {CascadeType.MERGE,CascadeType.REFRESH}, optional=false)//可选属性optional=false,表示product不能为空。删除文章,不影响用户
    @JoinColumn(name = "specs_id")//设置在specification表中的关联字段(外键)
    private Specification specification;//关联规格属性

商品表:

    @OneToMany(mappedBy = "product",cascade = CascadeType.ALL,fetch = FetchType.LAZY)
    private List<SpecsProduct> specsList;//规格关联列表

属性表:

@OneToMany(mappedBy = "specification",cascade = CascadeType.ALL,fetch = FetchType.LAZY)
private List<SpecsProduct> specsTotalList;//一对多关联

springboot reflect运行日志:添加两外键

Hibernate: alter table specs_total add constraint FKl9nk1ft75g2hb2o8jfofnahup foreign key (product_id) references product (id)
Hibernate: alter table specs_total add constraint FKevim9bddua610ajqnal48geaw foreign key (specs_id) references specification (id)

数据库运行结果:

简单商品表的findAll查询结果:

{
    "success": true,
    "code": 200,
    "message": null,
    "data": [
        {
            "remark": null,
            "create_datetime": "2022-09-17T16:11:34",
            "create_user": "1",
            "last_update_datetime": null,
            "last_update_user": null,
            "id": "1",
            "product_name": "iphone  x14",
            "type_id": "xxxx1",
            "price": 8000.0,
            "stock": 10000,
            "product_pic_urls": "http:localhost:8888/xxxxxx/xxx.jpeg;http:localhost:8888/xxxxxx/xxx.jpeg",
            "product_detail_pic_urls": "xxxxxx;xxxxx1q",
            "onSale": "",
            "isNew": "",
            "specsList": []
        },
        {
            "remark": null,
            "create_datetime": "2022-09-17T16:11:34",
            "create_user": "1",
            "last_update_datetime": null,
            "last_update_user": null,
            "id": "20220917T001663BPa40b64fa",
            "product_name": "高质量防脱洗发水。。。",
            "type_id": "ss22x",
            "price": 8000.0,
            "stock": 6666,
            "product_pic_urls": "http:localhost:8888/xxxxxx/xxx.jpeg;http:localhost:8888/xxxxxx/xxx.jpeg",
            "product_detail_pic_urls": "xxxxxx;xxxxx1q",
            "onSale": "",
            "isNew": "",
            "specsList": []
        }
    ]
}

猜想:

可以不写任何外键,直接映射后连接查询。

 

posted @ 2022-10-25 16:22  曦灰  阅读(715)  评论(0)    收藏  举报