简体   繁体   English

在ManyToMany上添加主键(用于发布)

[英]Add Primary key on ManyToMany (for Publication)

I have a ManyToMany relation between two entity 我在两个实体之间有一个ManyToMany关系

@javax.persistence.Entity
@Table(name = "t_aircraft_model")
public class AircraftModel extends DbObject {

    @ManyToMany(fetch=FetchType.LAZY)
    @JoinTable(name = "t_aircraft_model_entity", joinColumns = { @JoinColumn(name = "aircraft_model_uid", nullable = false) }, inverseJoinColumns = { @JoinColumn(name = "entity_id_LDAP", nullable = false) })
    private List<com.airbushelicopter.ahead.db.pojo.Entity> entities ;

But sqlServer doesn't allow me to publish the intermediate table : t_aircraft_model_entity 但是sqlServer不允许我发布中间表:t_aircraft_model_entity

新出版物

I thought about 2 solutions 我考虑了2个解决方案

  • Both column of the table the t_aircraft_model_entity become the primary key (ok in my case a aircraft can't be linked multiple time to the same entity) t_aircraft_model_entity表的两列都成为主键(在我的情况下,飞机无法多次链接到同一实体)
  • I add a 3rd column (id) which will be the primary key 我添加了第三列(id),它将作为主键
  • Or ? 要么 ?

But I have no idea how I can do this with hibernate and annotation. 但是我不知道如何使用休眠和注释来做到这一点。

thanks ! 谢谢 !

First things first. 首先是第一件事。 You will need 3 tables to make a many to many relation, of course, you will need to make sure that both of your other tables have a PK 您将需要3个表以建立多对多关系,当然,您需要确保其他两个表都具有PK

On the code side, you can do like this: 在代码方面,您可以这样做:

Your Airplace Model: 您的飞机模型:

@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
@JoinTable(name = "t_aircraft_entity_relation",joinColumns = {
        @JoinColumn(name = "aircraftid", nullable = false, updatable = false)},
        inverseJoinColumns = { @JoinColumn(name = "entityid",nullable = false,updatable= false)         
})
private Set<com.airbushelicopter.ahead.db.pojo.Entity> entities ;

On your Entity Model: 在您的实体模型上:

@ManyToMany(fetch = FetchType.EAGER,mappedBy="entities")    
private Set<AircraftModel> aircrafts;

And you will have to create a relation table, like in my example: 您将必须创建一个关系表,例如在我的示例中:

CREATE TABLE t_aircraft_entity_relation
(
  aircraftid integer NOT NULL,
  entityid integer NOT NULL,
  CONSTRAINT "PK_AIRCRAFT_ENTITY" PRIMARY KEY (aircraftid, entityid),
  CONSTRAINT "FK_AIRCRAFT_ENTITY" FOREIGN KEY (aircraftid)
      REFERENCES t_aircraft_model (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT "FK_ENTITY_AIRCRAFT" FOREIGN KEY (entityid)
      REFERENCES t_entity_model (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

PS: This piece of SQL is based on Postgresql, so you will have to do a little bit of change. PS:这部分SQL基于Postgresql,因此您将需要做一些更改。

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

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