0

I have 2 entities: A and B.

@Entity
@Table(name = "A")
class A{
    @Id
    private long id;

    @OneToMany(mapped by="a")
    private Set<B> b;
}

@Entity
@Table(name = "B")
class B{
    @Id
    private long id;

    @ManyToOne
    @JoinColumn(name="a")
    private A a;
}

When i'm trying to make something like

Query q=sessionFactory.openSession().createQuery("select a.id, bArray
 from A as a join a.b as bArray");

i'm getting not collection of B, but one B-object. How can i get A-class and collection of related with it B-objects? I.e. in debugger there is not Set with 1 element, there is just B-element.

1
  • select distinct a from A a left join fetch a.b will return the As, each with its loaded set of Bs. There's no way to do what you want. Commented Aug 31, 2015 at 12:42

1 Answer 1

2
Query q=sessionFactory.openSession().createQuery("select a.id, bArray
 from A as a join a.b as bArray");

With above query, you will get only one object for B not a collection because basically the query is just performing the join between A and B and returning all the possible tuples ( select a , b from A as a inner join B as b)

You can set a custom result transformer for custom results processing like this

But anyway in your case, you can simply pre-fetch "b" objects along with "a" object by using join fetch as below query.

Query q=sessionFactory.openSession().createQuery("select a from A as a join fetch a.b ");
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.