Erhan Bagdemir
Erhan Bagdemir

Reputation: 5327

Hibernate Annotations/JPA mapping collections

my problem is about mapping collections with JPA annotations in Hibernate. Say, i have an entity:

@Entity
@Table(name="orders")
class Order {
@Id @GeneratedId private Long id;
@OneToMany(fetch=FetchType.EAGER, targetEntity=Item.class)
@JoinColumn(name="order_id")
private List<Item> items;
/* getters setters */
}

and my item:

@Entity
@Table(name="items")
class Item {
@Id @GeneratedId private Long id;
@ManyToOne
@JoinColumn(name="order_id")
private Order order;
/* getters setters */
}

order_id is the foreign key in the items table which reference to an order with that id. if i have 3 items for an order in the items table, i get three orders object instead of one with three items in the items collection, if i query with :

Query query = query.createQuery("from Order o where o.id=:id");
query.setLong("id", 1234L);
List<Order> orders = query.list();

query.list() returns three order instances. How can i map such basic collections with hibernate 3.5.x? The result of list() is like a result returned by a SQL statement on DB. How can i say Hibernate/JPA, that it should return one order object with three items in the collection?

Thank you all

UPDATE: the association is unidirectional. that means, order table has no information about items.

Upvotes: 2

Views: 5009

Answers (1)

Rich Kroll
Rich Kroll

Reputation: 4005

You need to specify the mappedBy, and remove the @JoinColumn on the order class:

@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue
private Long id;

@OneToMany(fetch = FetchType.EAGER, mappedBy = "order")
private List<Item> items;

// accessors
}


@Entity
@Table(name = "items")
public class Item {
@Id
@GeneratedValue
private Long id;

@ManyToOne
@JoinColumn(name = "order_id")
private Order order;
    // accessors
}

Upvotes: 4

Related Questions