How to create a hibernate order with properties in another table?
-
08-04-2021 - |
Frage
I'm trying to create an order on a table and one of the items to be 'ordered by' happens to be a property that's in the one end of the relationship.
Do I specify the property by the name of the key, the name of the property (in the foreign table) or the name of the table?
Currently have:
order = new Order[]{Order.asc("lastControlDate"), Order.asc("idManufacturer"), Order.asc("model")};
where in idManufacturer is the foreign key
Thanks
The entities are Manufacturer 1..M Car wherein:
Manufacturer:
public class Manufacturer{
private Long idManufacturer;
private String name;
//<editor-fold defaultstate="collapsed" desc="Constructors">
public Manufacturer(){
//getters and setters....
}
Car:
public class Car {
private long idCar;
private String model;
private Manufacturer manufacturer;
//Constructor, getters and setters...
}
order = new Order[]{ Order.desc("manufacturer"), Order.desc("model")};
public static List<Car> listCarsByManufacturer(Manufacturer name, Order...orders)throws Exception{
LinkedList<Criterion> criterions = new LinkedList<Criterion>();
criterions.add(Restrictions.like("Car.manufacturer", name));
List<Car> cars =carDAO.findAllCars(criterions, orders);
return cars;
}
Lösung
You still haven't shown us the query, in CarDAO.findAllCars()
.
Anyway, here's how you get a list of cars with a retriction on their manufacturer name and an order on their manufacturer ID:
Criteria c = session.createCriteria(Car.class, "car");
// to add a restriction on a property of manufacturer, you need
// an inner join on manufacturer
c.createAlias("car.manufacturer", "manufacturer");
c.add(Restrictions.like("manufacturer.name", name));
// you want to get the car with their manufacturer, so you need a fetch
c.setFetchMode(car.manufacturer", FetchMode.JOIN);
// you want to order by id of manufacturer
c.addOrder(Order.asc("manufacturer.idManufacturer"));
All this is very well explained in the Hibernate reference manual.