Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Hibernate: When to use @OneToMany?

Guy Yafe
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

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?

Amritendu De
Ranch Hand
Posts: 188
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.
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!