• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hibernate: When to use @OneToMany?

 
Guy Yafe
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have a database which has an implicit @OneToMany association:
I have a table of items: Earrings, Shirts, Pants, etc..
Another table is called attribute_types and represents the type of attributes an item can get.

Example:
The attribute_types table contains the values 'colors' and 'sizes'.
The Earring item has the attribute_type field set to 'color' because an earring can come in several colors.
Pants and Shirt have both attribute_type 'sizes' because each can have many sizes.
Each item has only one attribute_type. This means for example that red shirt and blue shirt are different items and represented by different rows in the items table. Although, each can have several sizes.

The association between the attribute_types and items is One-To-Many: Each attribute_type has many items associated with it, and each item has exactly one attribute_type.

My question is how to annotate this relation?
On the Item object side, there is a @ManyToOne annotation on the attributeType field.
But what about the AttributeType object? Obviously there is no point having each AttributeType instance hold a collection of all the items associated with it because it is irrelevant. So Do I need to use this side's @OneToMany annotation anyway, or can I omit it?

Thanks,
Guy
 
Amritendu De
author
Ranch Hand
Posts: 188
11
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you choose to make it unidirectional, you just need the @OneToMany and the @JoinColumn annotations. If you make it bidirectional, you also need the @ManyToOne annotation. This is given very clearly in my recent book.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic