Caesar Ralf
Caesar Ralf

Reputation: 2233

Criteria fetch @ManyToOne relationship partially

Is there a way to fetch an associated ManyToOne associated entity partially only using criteria?

I have the following case

@Entity
public class Foo {
    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    private Bar bar;
    // getters/setters and lots other attributes
}

@Entity
public class Bar {
    private String name;
    @OneToMany(fetch = FetchType.EAGER)
    private Collection<ComplexObject> complexObjects;
    // getters/setters
}

And I have a Criteria that selects all my Foo's and I want fetch together with it only the name of the Bar associated to it. I don't want the collection of ComplexObjects to be loaded together. Is there a way to accomplish that without modifying Bar?

I want this because I want to show to the user something like

      Foo.Attr1, Foo.Attr2, Foo.Bar.Name

Upvotes: 0

Views: 416

Answers (1)

JB Nizet
JB Nizet

Reputation: 691993

No, it's impossible. When you mark a collection as eagrely fetched, it's always eagerly fetched. If you want it lazily loaded, it should be marked lazy.

But you may select only your three attributes:

Criteria c = session.createCriteria(Foo.class, "foo");
c.createAlias("foo.bar", "bar");
c.setProjection(Projections.projectionList().add(Projections.property("foo.attr1"))
                                            .add(Projections.property("foo.attr2"))
                                            .add(Projections.property("bar.name")));

Or, much more readable:

String hql = "select foo.attr1, foo.attr2, bar.name from Foo foo"
             + " inner join foo.bar bar";

Upvotes: 1

Related Questions