标准与投影相结合

Criteria join with projection

我将创建此 SQL 查询的 Criteria 等效项:

SQL:

SELECT
  orders.id,
  book.title,
  orderitem.quantity

  FROM orderitem
    INNER JOIN book ON book.id = orderitem.book_id
    INNER JOIN orders ON orders.id = orderitem.orders_id

WHERE user_id = 1

这是我的 Criteria 查询:

Criteria c = getSession().createCriteria(OrderItem.class, "oi");
c.setProjection(Projections.property("quantity"));

c.createAlias("oi.book", "book");
c.setProjection(Projections.property("title"));
c.createAlias("oi.orders", "or");
c.setProjection(Projections.property("id"));
c.createAlias("or.user", "usr");

c.add(Restrictions.eq("usr.id", "1"));
return c.list();

它没有异常,但它只显示 Orders.id 列:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 22]

使用ProjectionList。它将 return 包含字段 quantity , title , id 的对象数组。

Criteria c = getSession().createCriteria(OrderItem.class, "oi");
c.createAlias("oi.book", "book");
c.createAlias("oi.orders", "or");
c.createAlias("or.user", "usr");

ProjectionList proList = Projections.projectionList();
proList.add(Projections.property("oi.quantity"));
proList.add(Projections.property("book.title"));
proList.add(Projections.property("or.id"));
c.setProjection(proList);
c.add(Restrictions.eq("usr.id", "1"));
return c.list();

我需要接收作为命名键和值而不是索引和值的结果列表。我使用了以下方式。

Criteria c = getSession().createCriteria(OrderItem.class, "oi");
c.createAlias("oi.book", "book");
c.createAlias("oi.orders", "or");
c.createAlias("or.user", "usr");

ProjectionList proList = Projections.projectionList();
proList.add(Projections.property("oi.quantity"), "quantity");
proList.add(Projections.property("book.title"), "title");
proList.add(Projections.property("or.id"), "id");
c.setProjection(proList);

c.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);

c.add(Restrictions.eq("usr.id", "1"));
return c.list();