Reputation: 3080
Right now I have an User entity which contains its specific fields like id, name, password. The user is also an owner of Item entities, which are in Many-to-one and vice-versa relationship:
@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
}
Due to many consistency problems related with such an organisation (bidirectional), I want manage them myself by properly implementing methods like addItem, removeItem etc. These are not directly related to User entity and I think I should move this responsibility to another class. I thought about:
@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
}
Is this possible to do with Hibernate? How can I map everything to properly populate these collections?
Another idea is to create a class which will retrieve User object and manage collections, but this one requires ownedItems and ownedConsumables fields to be exposed via getters. Seems a worse one.
Upvotes: 1
Views: 772
Reputation: 692211
You can do that by annotating the class with @Embeddable
, and the field inventory
with @Embedded
.
Upvotes: 1