@Entity
public class car {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id_car;
@OneToOne
private repair id_repair;
}
@Entity
public class repair {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id_repair;
@OneToOne
@JoinColumn(name="id_car")
private car id_car;
}
我写了sql查询,这是我想收到的东西
SELECT id_car,
COUNT(*) AS c
FROM repair
GROUP BY id_car
ORDER BY c DESC
LIMIT 5
如何使用Hibernate实现这一目标?我希望获得'id_car'和出现次数。
答案 0 :(得分:0)
List results = session.createCriteria(Car.class)
.setProjection( Projections.projectionList()
.add( Projections.rowCount(),"rCount")
.add( Projections.groupProperty("id_car") )
)
.addOrder(Order.desc("rCount") )
.setMaxResults(5)
.list();
答案 1 :(得分:0)
Criteria cr = session.createCriteria(Repair.class)
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("id_car"))
.add(Projections.rowCount(), "rCount"))
.addOrder(Order.asc("rCount"))
.setMaxResults(5);
if(cr.list().size() > 0) {
for(Object o : cr.list()) {
Object[] row = (Object[]) o;
// Here row[0] will have id_car and
// row[1] will have the number of entry in the database.
}
}