现在我有一个 User 实体,其中包含其特定字段,如 id、name、password。用户也是 Item 实体的所有者,它们是多对一关系,反之亦然:
@Entity
@Table(name="users")
public class User {
/* Id, name, password etc - strictly User specified */
private List<Item> ownedItems;
private List<Bike> ownedConsumables;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "owner")
@Fetch(FetchMode.SELECT)
public List<Item> getOwnedItems() {
return ownedItems;
}
@OneToMany(fetch = FetchType.EAGER, mappedBy = "owner")
@Fetch(FetchMode.SELECT)
public List<Consumable> getOwnedConsumables() {
return ownedConsumables;
}
// a lot of methods to manage collections to keep one-to-many consistency
// which are not related to strictly to User entity
}
由于与此类组织(双向)相关的许多一致性问题,我想通过正确实现 addItem、removeItem 等方法来自行管理它们。这些与 User 实体没有直接关系,我认为我应该将此责任移交给另一个类(class)。我想到了:
@Table(name="users")
public class User {
/* Id, name, password etc - strictly User specified */
private Inventory inventory;
}
public class Inventory {
private User owner; // if needed - I think it will
private List<Item> ownedItems;
private List<Bike> ownedConsumables;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "owner")
@Fetch(FetchMode.SELECT)
public List<Item> getOwnedItems() {
return ownedItems;
}
@OneToMany(fetch = FetchType.EAGER, mappedBy = "owner")
@Fetch(FetchMode.SELECT)
public List<Consumable> getOwnedConsumables() {
return ownedConsumables;
}
// a lot of methods to manage collections to keep one-to-many consistency
}
这可能与 Hibernate 有关吗?如何映射所有内容以正确填充这些集合?
另一个想法是创建一个类来检索 User 对象并管理集合,但这需要通过 getter 公开ownedItems 和ownedConsumables 字段。看起来更糟糕。
最佳答案
您可以通过使用 @Embeddable
注释该类并使用 @Embedded
注释字段 inventory
来实现此目的。
关于java - Hibernate - 将关系及其管理委托(delegate)给子类以保持整洁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43868964/