我尝试使用多对多的方法产品与商店有多对多的关系 的 Product.java
package models;
@Entity
public class Product extends Model {
@Id
@SequenceGenerator(name="product_gen", sequenceName="product_id_seq", allocationSize=1)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="product_gen")
@Column(name="id")
public Long id;
@Required
public String name;
@Required
public Float price;
@ManyToMany(cascade = CascadeType.ALL)
public List<Shop> shops = new ArrayList<Shop>();
public Product(String name, float price) {
this.name = name;
this.price = price;
}
public static List<Product> all(){
return find.all();
}
public static Model.Finder<Long, Product> find = new Model.Finder(Long.class, Product.class);
public static Product create(String name,float price) {
Product product = new Product(name, price);
product.save();
product.saveManyToManyAssociations("shops");
return product;
}
}
play创建了一个table_shop表,其中shop_id和product_id为外键,但在添加产品时无法在product_shop表中存储任何值 任何帮助将不胜感激。
答案 0 :(得分:4)
我有Apps
和Users
。每个应用程序可以有多个用户,每个用户可以使用多个应用程序。
在您的情况下,您可以将App
替换为Product
,将User
替换为Shop
这是Play下的工作代码! 2.2.2
DB的演变:
create table app_user (
id varchar(40) not null,
constraint pk_fb_user primary key (id)
);
create table app (
id varchar(40) not null,
name text,
constraint pk_app_id primary key (id)
);
create table membership (
app_id varchar(40) not null,
app_user_id varchar(40) not null,
constraint fk_membership_app_id foreign key (app_id) references app,
constraint fk_membership_app_user_id foreign key (app_user_id) references app_user
);
模型应用
@Entity
public class App extends Model {
@Id
public UUID id;
@Column
public String name;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "membership")
public List<User> users;
....
}
模型用户
@Entity
@Table(name = "app_user")
// user is reserved keyword in DB
public class User extends Model {
@Id
public UUID id;
}
我不需要访问用户的应用,因此我在用户中没有应用字段。
答案 1 :(得分:-1)
尝试查看嵌入式ID。
为您的主键创建课程
@Embeddable
public class ProductShopKey {
public Long productId;
public Long shopId;
public boolean equals(Object object) {
if(object isInstanceOf ProductShopKey){
ProductShopKey key = (ProductShopKey) object
if(this.productId == key.productId
&& this.shopId == key.shopId
){
return true;
}
}
return false;
}
public int hashCode() {
return productId.hashCode() + shopId.hashCode();
}
}
然后为类
创建一个实体@entity
public class ProductShop {
@EmbeddedId
public ProductShopKey psKey = new ProductShopKey();
@ManyToOne
@JoinColumn(name = "product_id")
public Product product;
@ManyToOne
@JoinColumn(name = "shop_id")
public Shop shop;
//Extra value to go in your join table
public String someValue;
...
}
然后Shop
和Product
与ProductShop
在表格中插入条目是手动完成的
ProductShop ps = new ProductShop();
ps.psKey.productId = someProductId;
ps.psKey.shopId = someShopId;
ps.someValue = someValue;
ps.save();