我在两个实体之间有一个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 ;
但是sqlServer不允许我发布中间表:t_aircraft_model_entity
我想到了2个解决方案
但是我不知道如何使用hibernate和annotation来做到这一点。
谢谢!
答案 0 :(得分:1)
首先要做的事情。你需要3个表来建立多对多的关系,当然,你需要确保你的其他两个表都有PK
在代码方面,你可以这样做:
你的Airplace模特:
@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 ;
在您的实体模型上:
@ManyToMany(fetch = FetchType.EAGER,mappedBy="entities")
private Set<AircraftModel> aircrafts;
你必须创建一个关系表,就像在我的例子中一样:
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:这条SQL基于Postgresql,所以你必须做一些改变。