简体   繁体   English

如何通过关联链接实体映射两个实体

[英]How to map two entities through an associate link entity

I need to keep record of various businesses their cities and their branches in each city. 我需要记录他们的城市和各个城市的分支机构的各种业务。 Each business might be in different cities and in each city might have different branches. 每个企业可能在不同的城市,每个城市可能有不同的分支。

Take a bank as an example . 以银行为例 It might be in cities A and B and in city A might have two branches and in city B only one. 它可能位于城市A和B,而城市A可能有两个分支,而城市B只有一个。

I suppose the branch table should have branchid and foreign keys of both primary keys of the join table. 我想分支表应该具有连接表的两个主键的branchid和外键。 In this way I can make sure no branch will be associate to more than one combination of city and business. 通过这种方式,我可以确保没有任何分支机构与多个城市和企业的组合相关联。

 Business       City
     \          /
  BusinessID CityID    <<join table has primary keys of Business and City tables
          |
        Branch
BranchID BusinessID CityID

Sample data 样本数据

Business Table          
1         
2       
3        

City Table
A
B
C

Join Table
Business_City
1         A
1         B
2         A
3         C

Branch Table
Business City   Branch
1          A      I1
1          A      I2
1          B      I6
2          A      I5
3          C      I3

As you can see businesses 1 and 2 are both in city A. Business 1 has two branches in city A whereas business 2 has just one branch etc. 如您所见,企业1和2都在城市A中。企业1在城市A中有两个分支,而企业2只有一个分支等。

How should I map the Branch to a Business and a City? 我该如何将分行映射到商业和城市?

This is how your mappings should look like: 这就是你的映射应该是这样的:

@Entity
public class Business {
    @Id
    private Long id;

    @OneToMany(mappedBy = "business")
    private Set<Branch> branches = new HashSet<>();
}

@Entity
public class City {
    @Id
    private Long id;

    @OneToMany(mappedBy = "city")
    private Set<Branch> branches = new HashSet<>();
}

@Entity
public class Branch {

    @Id
    private Long id;

    @ManyToOne
    @JoinColumn(name = "business_id")
    private Business business;

    @ManyToOne
    @JoinColumn(name = "city_id")
    private City city;
}

This intermediate Entity mapping is better than using a @ManyToMany association which might generate some less efficient SQL queries and would not allow you to add some additional columns to the link table. 此中间实体映射优于使用@ManyToMany关联,这可能会生成一些效率较低的SQL查询,并且不允许您向链接表添加一些其他列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM