我有一张有一组字段和外键的桌子。
在使用Ebean时,我可以指定要填充请求的字段,首先是以外部关系结束的id (并不总是需要类中数据库中的所有字段)。它只使用一个与表绑定的类。
@Entity
public class Product extends Model{
@Id
public Long id;
@Constraints.Required
public String name;
@Lob
public String description;
@ManyToOne
public Trademark trademark;
...
}Q1.在使用Anorm时,鼓励使用case class,但我需要指定case class的所有可能字段并填充它们。如果我只需要一个只有字段Id和Name的对象,还是只需要Id的ref对象呢?我还要描述另一堂课吗?
case class ProductRef (id: Pk[Long] = NotAssigned)
case class Product (id: Pk[Long] = NotAssigned, name: String)
case class ProductWithTrademark (id: Pk[Long] = NotAssigned, name: String, trademark: Trademark)
...
case class Trademark (id: Pk[Long] = NotAssigned, name: String ="")Q2.如果您可以在另一个表中使用此表作为外键,怎么办?使用哪一种case class?
case class Size(id: Pk[Long] = NotAssigned, name: String)
case class ProductSize(id: Pk[Long] = NotAssigned, product: ??? , size: Size)Q3.或者,最好总是用默认值填充所有字段,并且只使用一个case class。
case class Product(id: Pk[Long] = NotAssigned, name: String="", trademark: Trademark = Trademark())
case class Trademark(id: Pk[Long] = NotAssigned, name: String="")
case class Size(id: Pk[Long] = NotAssigned, name: String = "")
case class ProductSize(id: Pk[Long] = NotAssigned, product: Product = Product(), size: Size = Size())Q4.或者有一个正确的决定,,我根本不知道
发布于 2014-03-16 11:52:45
当表中有几个可以为空的字段时,通常的做法是在case类中将它们设置为选项。例如,与其拥有:
case class Product (id: Pk[Long] = NotAssigned, name: String)
case class ProductWithTrademark (id: Pk[Long] = NotAssigned, name: String, trademark: Trademark)你可能会:
case class Product (id: Pk[Long] = NotAssigned, name: String, trademark: Option[Trademark])然后将产品解析器设置为检查Trademark是否存在。
Play附带的computer-database示例描述了完全相同的情况。在该示例中,他们使用以下案例类来描述它们的模型:
case class Company(id: Pk[Long] = NotAssigned, name: String)
case class Computer(id: Pk[Long] = NotAssigned, name: String, introduced: Option[Date], discontinued: Option[Date], companyId: Option[Long])您可以看到外键被设置为Option,因为Computer模型可以(没有)链接到它的Company。然后对Computer解析器进行如下描述:
val simple = {
get[Pk[Long]]("computer.id") ~
get[String]("computer.name") ~
get[Option[Date]]("computer.introduced") ~
get[Option[Date]]("computer.discontinued") ~
get[Option[Long]]("computer.company_id") map {
case id~name~introduced~discontinued~companyId => Computer(id, name, introduced, discontinued, companyId)
}
}注意如何在解析外键时使用get[Option[Long]]。公司解析器是以相同的方式定义的,当希望同时获得Computer和Company (如果设置了外键company_id )时,它们使用以下解析器返回元组(Computer,Option[Company])
val withCompany = Computer.simple ~ (Company.simple ?) map {
case computer~company => (computer,company)
}https://stackoverflow.com/questions/22434558
复制相似问题