Hibernate Criteria加入最新状态并过滤结果

时间:2016-04-18 16:24:29

标签: java hibernate hibernate-criteria

我有一个Orders表,以及一个指向order.id的Order Status Updates表。我需要获得订单列表,但我需要加入订单状态更新,因为我不希望最后状态为“已取消”的订单

CREATE TABLE `orders` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`end_customer_id` bigint(20) NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `FK_end_customer` (`end_customer_id`),
CONSTRAINT `orders_ibfk_3` FOREIGN KEY (`end_customer_id`) REFERENCES `end_customers` (`id`) ON UPDATE CASCADE,
) ENGINE=InnoDB AUTO_INCREMENT=100333 DEFAULT CHARSET=utf8;


CREATE TABLE `order_status_updates` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `status` varchar(255) NOT NULL,
  `date` datetime NOT NULL,
  `order_id` bigint(20) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `FK_order` (`order_id`),
  CONSTRAINT `order_status_updates_ibfk_3` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
) ENGINE=InnoDB AUTO_INCREMENT=344180 DEFAULT CHARSET=utf8;

目前的标准是:

final Criteria c = criteria("o")
    .add(eq("o.endCustomer.id", endCustomerId));
return list(c.addOrder(desc("createdAt")));

我需要过滤掉最新状态(按日期排序)取消的订单

1 个答案:

答案 0 :(得分:1)

假设有一个名为MyOrderORDER_STATUS枚举以及idstatuscreatedAt字段定义的类:

final Criteria c = sessionFactory.getCurrentSession().createCriteria(MyOrder.class);

c.add(Restrictions.eq("id", yourId))
 .add(Restrictions.ne("status", ORDER_STATUS.CANCELLED)
 .addOrder(Order.desc("createdAt"));