【发布时间】:2013-12-16 12:33:32
【问题描述】:
我在 MySQL Workbench 中创建了一个模式:
如何在 Play Framework 中将其映射到 Ebean 中的实体?在教程中,他们使用方法编写模型类,使用@Entity 对其进行注释并让 Play 生成 SQL 脚本,但不关心数据类型(例如如何设置 VARCHAR 的限制)。
多对多关系呢?在我的情况下 - 我应该创建一个实体类 UsersScenarios 还是应该创建一个 Scenario 模型,其中包含一个包含 Users 对象集合的字段和一个包含 Scenario 对象集合的 User 模型?或者也许我应该在 MySQL Workbench 中生成模式并以某种方式将其映射到我的应用程序中?
请帮助我,因为我没有任何 ORM 经验。
编辑:我用两个模型做了一个小测试:
EntityA.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
);
}
EntityB.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的表?
【问题讨论】:
标签: mysql orm playframework ebean playframework-2.2