我在 MySQL Workbench 中创建了一个模式:
我如何将其映射到 Play Framework 中 Ebean 中的实体?在教程中,他们使用方法编写模型类,用 @Entity
注释并让 Play 生成 SQL 脚本,但不关心数据类型(例如如何对 VARCHAR 设置限制)。
多对多关系呢?在我的例子中 - 我应该创建一个实体类 UsersScenarios
还是应该创建一个 Scenario
模型,其中包含一些包含 Users
对象集合的字段和一个User
模型包含一组 Scenario
对象?或者我应该在 MySQL Workbench 中生成模式并以某种方式将其映射到我的应用程序中?
请帮助我,因为我没有任何 ORM 经验。
编辑:我用两个模型做了一个小测试:
实体A.java:
package models;
import java.util.*;
import play.db.ebean.*;
import play.data.validation.Constraints.*;
import javax.persistence.*;
@Entity
public class EntityA extends Model {
@Id
public Long id;
@Required
public String label;
@ManyToMany
public List<EntityB> entitiesB = new ArrayList<EntityB>();
public static Finder<Long,EntityA> find = new Finder(
Long.class, EntityA.class
);
}
实体B.java
package models;
import java.util.*;
import play.db.ebean.*;
import play.data.validation.Constraints.*;
import javax.persistence.*;
@Entity
public class EntityB extends Model {
@Id
public Long id;
@Required
public String label;
@ManyToMany
public List<EntityA> entitiesA = new ArrayList<EntityA>();
public static Finder<Long,EntityB> find = new Finder(
Long.class, EntityB.class
);
}
生成的 SQL 演变:
create table entity_a (
id bigint auto_increment not null,
label varchar(255),
constraint pk_entity_a primary key (id))
;
create table entity_b (
id bigint auto_increment not null,
label varchar(255),
constraint pk_entity_b primary key (id))
;
create table entity_a_entity_b (
entity_a_id bigint not null,
entity_b_id bigint not null,
constraint pk_entity_a_entity_b primary key (entity_a_id, entity_b_id))
;
create table entity_b_entity_a (
entity_b_id bigint not null,
entity_a_id bigint not null,
constraint pk_entity_b_entity_a primary key (entity_b_id, entity_a_id))
;
alter table entity_a_entity_b add constraint fk_entity_a_entity_b_entity_a_01 foreign key (entity_a_id) references entity_a (id) on delete restrict on update restrict;
alter table entity_a_entity_b add constraint fk_entity_a_entity_b_entity_b_02 foreign key (entity_b_id) references entity_b (id) on delete restrict on update restrict;
alter table entity_b_entity_a add constraint fk_entity_b_entity_a_entity_b_01 foreign key (entity_b_id) references entity_b (id) on delete restrict on update restrict;
alter table entity_b_entity_a add constraint fk_entity_b_entity_a_entity_a_02 foreign key (entity_a_id) references entity_a (id) on delete restrict on update restrict;
看来进化脚本并不完美——为什么我需要两个连接EntityA
和EntityB
的表?
最佳答案
对于 ManyToMany 关系,您需要定义关系的所有者。
在你的情况下应该是这样的:
@ManyToMany(mappedBy = "entitiesA")
public List<EntityB> entitiesB = new ArrayList<EntityB>();
使用mappedBy,它只会生成一个桥接表。
再看看这些问题,它们会给你更多的理解:
关于mysql - Ebean 和多对多关系 - 怎么样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20611067/