我正在尝试将此SQL查询转换为Hibernate Criteria,但我不太确定我对Hibernate的新手是什么。
SELECT header.*,
(SELECT items.end_date from
subTable sub,
ItemTable items
WHERE items.sub_id = sub.sub_id
and header.header_id = sub.header_id
order by items.end_date desc
limit 1) as latestEndDate
from headerTable header
order by latestEndDate desc;
我可以创建子查询,但我对如何将其合并到主查询中感到茫然。
Long headerId = getHeaderId();
Criteria criteria = session.createCriteria(dataaccess.model.Item.class, "item");
DetachedCriteria headerSubQuery =
DetachedCriteria.forClass(dataaccess.model.Header.class, "header")
.setProjection(Property.forName("header.headerId"))
.add(Restrictions.eq("headerId, headerId));
DetachedCriteria subTableQuery =
DetachedCriteria.forClass(dataaccess.model.SubTable.class, "sub")
.setProjection(Property.forName("sub.subId)).add(
Property.forName("header").in(headerSubQuery));
criteria.add(Property.forName("sub").in(subTableQuery));
criteria.addOrder(Order.desc("endDate"));
criteria.setMaxResults(1);
List<Items> items = criteria.list();
* HeaderTable和SubTable具有1:1的关系,并且只是出于遗留原因而存在。 SubTable拥有Items,但由于1:1的关系,HeaderTable还拥有Items(HeaderTable - &gt; SubTable - &gt; Items)。
该查询返回具有最新endDate的项目。我希望能够使用Hibernate查询头表并使用最新的endDate对其中一个项进行排序(如上面的SQL查询)。
感谢您的帮助。
答案 0 :(得分:2)
我最后通过在我的Header模型中添加另一个字段并使用@Formula注释传递我的SQL查询来解决这个问题。
var delegate: NewLocationViewControllerDelegate!
var contacts = [CNContact]()
override func viewDidLoad() {
super.viewDidLoad()
UIApplication.sharedApplication().delegate as! AppDelegate
// Do any additional setup after loading the view.
}//end
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func openContacts(sender: UIButton) {
let contactPicker = CNContactPickerViewController()
contactPicker.delegate = self;
contactPicker.displayedPropertyKeys = [CNContactPhoneNumbersKey]
self.presentViewController(contactPicker, animated: true, completion: nil)
}//end
func contactPicker(picker: CNContactPickerViewController, didSelectContactProperty contactProperty: CNContactProperty) {
let contact = contactProperty.contact
let phoneNumber = contactProperty.value as! CNPhoneNumber
print(contact.givenName)
print(phoneNumber.stringValue)
}//end
这允许我在我的标准下附加订单:
@Formula("(SELECT items.end_date from "
+ "subTable sub, "
+ "ItemTable items "
+ "WHERE items.sub_id = sub.sub_id "
+ "and header.header_id = sub.header_id "
+ "order by items.end_date desc "
+ "limit 1)")
private Date latestStartDate;
public getLatestStartDate() {
return latestStartDate;
}