【问题标题】:Manytoone mapping for two tables to the single entity将两个表的多对映射映射到单个实体
【发布时间】:2022-01-23 22:35:45
【问题描述】:
Class A{
private int campid;
private string name;
}

Class B {
Private int campid;
Private string name;
}`


Class combo{
private int id;
private string phonenumber;
}

我正在尝试这样

Class A{
private int campid;
private string name;
@OneToMany(targetEntity = Combo.class,mappedBy ="a",fetch = FetchType.LAZY,cascade=CascadeType.ALL )
private Combo combo;
}

Class B {
Private int campid;
Private string name;
@OneToMany(targetEntity = Combo.class,mappedBy ="b",fetch = FetchType.LAZY,cascade=CascadeType.ALL )
private Combo combo;
}`

Class combo{
private int id;
private string phonenumber;
@ManyToOne
@JoinColumn(name = "Camp_Id_fk",insertable=true, updatable=true)
private  A a;
    
@ManyToOne
@JoinColumn(name = "Camp_Id_fk",insertable=true, updatable=true)
private B b;
}

想将A类和B类的campid作为外键存储在组合表中。一个campid可以有多个电话号码。

我想在春季 jpa 中执行此操作..我不明白该怎么做

【问题讨论】:

  • 你尝试了什么?你看过@ManyToMany注解吗?向我们展示你的试验。
  • 为了帮助人们快速了解您想要实现的目标,最好用简短的摘要而不是代码块来打开您的问题。

标签: spring-boot hibernate spring-mvc spring-data-jpa spring-data


【解决方案1】:
@Entity
@Table(name = "a")
public class A {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "camp_id")
    private Long campid;

    @Column(name = "name")
    private String name;

    @Column
    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
    @JoinTable(name = "a_combo",
            joinColumns = @JoinColumn(name = "camp _id"),
            inverseJoinColumns = @JoinColumn(name = "id"))
    private Set<Combo> comboSet = new HashSet<>();
}

B类也一样

【讨论】:

  • 它将如何映射到表格组合
  • 将是“a and combo”和“b and combo”“a_combo”、“b_combo”关系的两张表,其中包含“camp_id”、“combo_id”
  • 我希望A表campid和b表campid都映射到组合表中作为同一列中的外键
猜你喜欢
  • 2015-01-07
  • 1970-01-01
  • 2012-04-21
  • 1970-01-01
  • 2019-04-19
  • 1970-01-01
  • 2015-08-17
相关资源
最近更新 更多