I have 2 classes similar to this:
public class A {
@Id @GeneratedValue
private long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "b_id")
B b;
...
}
public class B {
@Id @GeneratedValue
private long id;
...
}
I want to make a query using the Criteria API that queries the A
table, but for future queries, having the id
of the b many to one relationship is important.
So far I've found I can use
var root = query.from(A.class);
root.fetch(A_.b);
...
When I look at the underlying SQL this produces, this will cause all basic attributes of B
to be fetched.
What I'm looking for is to (without falling back on HQL) do something like
var root = query.from(A.class);
root.join(A_.b).fetchBasicAttribute(B_.id);
...
Resulting in instances of A
linking to instances of B
where only the id
is populated. (Ideally I'd also like to be able to specify other attributes of B too)
Is something like this possible?
That's not really possible with Hibernate right now. Note though that the primary key i.e. id
attribute is the one that the foreign key column refers to, so you don't have to fetch that attribute, it will be populated in the proxy object that is created automatically.