我有以下两种型号;国家和州
class Country extends Model {
//country has many states
}
class State extends Model{
//state belongs to country
}
在我的场景中,一个国家有很多州,我希望用户可以根据需要创建和添加任意数量的州。
我是新手来玩框架并寻找一个继承表单的好例子,以便用户可以动态添加多个状态子表单并保存/编辑它们。
我真的很感激上面一个简单的示例表格。
答案 0 :(得分:0)
使用鉴别器值,这样做。我还没有厌倦用Ebean继承,我不明白为什么在使用TablePerClass策略时需要使用鉴别器(因为我在下面使用,但是在没有它的情况下我得到了错误)。 OpenJPA有一些其他的例子。 Ebean遵循大多数JPA,因此它可能无法完全像JPA那样工作,您将不得不尝试查看。
package models.test;
import play.db.ebean.Model;
import javax.persistence.*;
/**
* Created by aakture on 3/12/14.
*/
@Entity
@Inheritance (strategy= InheritanceType.TABLE_PER_CLASS)
@DiscriminatorValue("S")
public class State extends Model {
@Id
protected Long id;
protected String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package models.test;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
/**
* Created by aakture on 3/12/14.
*/
@Entity
@DiscriminatorValue("MS")
public class MyState extends State {
String addedProperty;
public String getAddedProperty() {
return addedProperty;
}
public void setAddedProperty(String addedProperty) {
this.addedProperty = addedProperty;
}
}
package models.test;
import play.db.ebean.Model;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.util.List;
/**
* Created by aakture on 3/12/14.
*/
@Entity
public class Country extends Model {
@Id
Long id;
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany (cascade = CascadeType.ALL)
List<State> states;
public List<State> getStates() {
return states;
}
public void setStates(List<State> states) {
this.states = states;
}
public static Model.Finder<Long, Country> find = new Model.Finder<Long, Country>(
Long.class, Country.class);
}
和测试:
@Test
public void testCountryState() {
Country country = new Country();
country.setName("Canada");
List<State> states = new ArrayList<State>();
State state = new State();
state.setName("This is a State");
states.add(state);
MyState mystate = new MyState();
mystate.setName("This is a MyState");
mystate.setAddedProperty("an added property");
states.add(mystate);
country.setStates(states);
country.save();
country = Country.find.where().eq("name", "Canada").findUnique();
}