one-to-many: making Hibernate select the reference's id instead of joining it
I have two classes stored in my database using Hibernate. Let's call them Container
and Item
. Item has a one-to-many relation to Container:
@entity(name = "containers")
public class Container {
@Id
@GeneratedValue
private long id;
}
@entity(name = "items")
public class Item {
@Id
@GeneratedValue
private long id;
@ManyToOne
@JoinColumn(name = "container_id")
private Container container;
}
I want to select select all for all items the tuple [ (long)item.id, (long)item.container_id ]
, but Hibernate seems to insist on retrieving [ (long)item.id, (Container)item.container ]
, introducing a useless (and expensive) join.
I tried that criteria query:
Criteria criteria = session.
createCriteria(Link.class).
add(Restrictions.isNotNull("container")).
setProjection(Projections.projectionList().
add(Projections.id()).
add(Projections.property("container")));
Is there a matching criteria query. Has to be possible without HQL queries or native SQL queries, hasn't it?
Edit 1: Working HQL query:
session.createQuery("SELECT item.id, item.container.id " +
"FROM items AS item " +
开发者_StackOverflow"WHERE item.container <> NULL")
Edit 2: FetchType.LAZY is not an option.
Criteria criteria = session.createCriteria(Link.class);
criteria.createAlias("container", "containerAlias");
criteria.add(Restrictions.isNotNull("containerAlias.id"));
criteria.setProjection(Projections.projectionList()
.add(Projections.id())
.add(Projections.property("containerAlias.id")));
It should be sufficient to add a fetch = FetchType.LAZY
attribute to the @ManyToOne
annotation. If you've annotated an ID
column in Container, the test for whether item.container
is null should not require a join.
精彩评论