2

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.

1 Answer 1

4

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.