4

I've got a shopping application with customers. Those customers have a cart containing products. Here's the (simplified) mapping with embeddables I used:

@Entity
class Customer {

  @Embedded
  private Cart cart;

  // Constructors, setters, equals... omitted
}

@Embeddable
class Cart {

  @ElementCollection
  @JoinTable(name = ...)
  private Set<Product> products = new HashSet<>();

  ...   
}

@Embeddable
class Product {

  private String name;

  ...
}

Now, I'm trying to get a customer's cart with HQL. I know I can't directly query embeddables, but nothing prevents me from selecting it as a field:

select c.cart from Customer c where c.id = 1

but this results in the following exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at org.hibernate.hql.ast.util.ColumnHelper.generateScalarColumns(ColumnHelper.java:62)
    at org.hibernate.hql.ast.tree.DotNode.setScalarColumnText(DotNode.java:661)
    at org.hibernate.hql.ast.tree.SelectClause.renderScalarSelects(SelectClause.java:359)
...

I could overcome this problem by just retrieving the customer and traverse its getCart() method, but I wonder if this issue is caused by an incorrect mapping or something like that. Thanks a lot!

user683887
  • 1,260
  • 1
  • 10
  • 20
  • try adding fetch=FetchType.EAGER annotation to private Cart cart; and private Set products = new HashSet<>(); – invariant Nov 12 '12 at 22:04
  • I tried with EAGER on Set (found no way I could add it to cart) but nothing changed. Thanks. – user683887 Nov 12 '12 at 23:05
  • How are you asking for the resultList? As List or as List or what? – carbontax Nov 13 '12 at 16:31
  • @carbontax: I'm asking for a single Cart object, so that's what I'm expecting: `Cart cart = (Cart) session.createQuery(...).uniqueResult()` – user683887 Nov 13 '12 at 22:03
  • The root of your query is Customer though. Not Cart. Do you have a reverse mapping from Cart to Customer? – carbontax Nov 14 '12 at 14:03
  • @carbontax No I don't. The cart is just a customer's property, the same as if you try to get only his name (`select name from Customer where...`) but in this case the property is an embeddable. – user683887 Nov 14 '12 at 15:04
  • Does the `Cart` object have any attributes that are mapped to columns? – Joaquim Oliveira Apr 05 '17 at 17:52
  • Hi Joaquim, this question is too old and I can't remember but I guess it had some attributes mapped to databases columns – user683887 Oct 17 '17 at 20:59

0 Answers0