我有一个实体PrintingFare
和那里的外键 - Printer
,
那么我如何以这种方式使用Criteria API,以便获得一组打印机,这些打印机具有打印票价?
基本上我有一个带有此字段的课程PrintingFare
@ManyToOne
@JoinColumn(name = "printer_id", foreignKey = @ForeignKey(name = "fk_fares_ref_printer_id"))
private Printer printer;
如何使用Criteria API获取一组打印机?
答案 0 :(得分:1)
您应该为查询添加限制
Criteria criteria = getSession().createCriteria(PrintingFare.class);
criteria.add(Restrictions.eq("printer.id", printerId));
List<PrintingFare> list = criteria.list();
Criteria criteria = getSession().createCriteria(Printer.class);
criteria.createAlias("printerFairs", "pf").add(Restrictions.in("pf.id", printerFairIds));
List<Printer> list = criteria.list();
答案 1 :(得分:1)
我还没有对此进行测试,但您可以尝试:
Criteria criteria = getSession().createCriteria(PrintingFare.class);
criteria.setProjection(Projections.distinct(Projections.property("printer"));
List<Printer> list = criteria.list();
让我知道它是否有效。它可能需要调整。
答案 2 :(得分:0)
如果PrinterFares是从Printer.class端映射的......
Criteria criteria = getSession().createCriteria(Printer.class);
criteria.createAlias("printerFares", "pf");
criteria.add(Restrictions.isNotEmpty("pf"));
crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
List<Printer> printers = criteria.list();
如果您无法更改Printer.class的映射...
Criteria criteria = getSession().createCriteria(Printer.class);
// create a subquery
DetachedCriteria dc = DetachedCriteria.forClass(PrinterFare.class);
dc.setProjection(Projections.property("printer.id"));
// restrict by subquery
criteria.add(Subqueries.in("id", dc);
crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
List<Printer> printers = criteria.list();