Search code examples
javajpajava-ee-5

What annotation should I use here ?@OneToMany or @OneToOne?


class StockPlace{
    private Stock stock;
    private Place place;
}

So this class describes a specific stock in a specific place, it can be changed with time.Like a place can contain another stock but at a given time only one stock is in a place and that place contains only that stock. I have troubles defining the annotation I should use, can anyone help?


Solution

  • Like a place can contain another stock but at a given time only one stock is in a place and that place contains only that stock

    You're a bit unclear, but if I get this right, you're speaking about situation where only one stock can be in a specific place?
    A place can contain another stock, but only after the original stock was removed from that place?
    I'm assuming that StockPlace will also be kind of an entity having current place of a single stock.

    If so, then go with @OneToOne for both fields, as it defines the relationship between classes, that only one row/record of StockPlace can exist for both Place and Stock and vice versa. Meaning, an unique stock and an unique place must be used when persisting StockPlace. Here, if you try persisting the StockPlace with a place or stock that already has been persisted. you'll get an exception.

    The @OneToMany annotation over a field, defines the relation between where an object declarding a field with that annotation can have many records mapped to it. It mostly (if not only) referes to that the class can have a collection of mapped items.
    For example, as described here a single shopping cart can contain of multiple items, so it maps the List<Item> with @OneToMany or a single article can have multiple comments.

    For covering a case where there's a possibility that more than one Stock will be in the same place, then the place field should be annotated with @ManyToOne as it indicates that single Place record can be assigned to many StockPlace records (therefore many stocks can be in a single place).

    I think, I really don't get such use case ;P Because in both cases where a single Place could could contain both multiple and single Stock, the Place could be declared inside the Stock class with OneToOne for unique Stock/Place combination or ManyToOne if single place could have multiple stocks at time.

    Take a look at this two SO posts:
    setting the correct jpa mapping for shopping cart items and product
    Hibernate ManyToOne vs OneToOne
    for a bit of different explanation and usage details over all of those three annotations.