I have a problem with hibernate and criterias. I have two Classes:
public class Place{
long id;
String name;
Set<Street> streets;
}
public class Street{
long id;
String name;
Place place;
}
I now want to write a method which returns a list of places with a name like given in parameters and a street named like given in parameters.
public List<Place> findPlaces(String name, String streetname){
//getSession() gives me a hibernate session
Criteria crit = getSession().createCriteria(Place.class, "place");
crit.add(Restrictions.like("name", name+"%"));
//Everything works fine until here
//Last step: Sort out all places not containing a street named like streetname + "%"
}
I tried different ways for the last step:
//streetList is a list of all streets named like streetname
crit.add(Restrictions.in("streets", streetList));
Another way:
DetachedCriteria strasseCrit = DetachedCriteria.forClass(Street.class, "street");
streetCrit.add(Restrictions.like("street.name", streetname + "%"));
streetCrit.createAlias("street.place", "streetPlace");
streetCrit.add(Restrictions.eqProperty("streetPlace.id", "place.id"));
streetCrit.setProjection(Projections.property("street.name"));
crit.add(Subqueries.exists(streetCrit));
last way:
crit.createAlias("place.streets", "street");
crit.add(Restrictions.like("street.name", streetname + "%"));
crit.setResultTransformer(DistinctResultTransformer.INSTANCE);
I hope you can understand my problem and sorry for my bad english :(
I searched for a solution for two days and I do not know how to go on...
Greetings form Germany :) Philipp
Since Hibernate 5.2, the Hibernate Criteria API is deprecated, and new development is focused on the JPA Criteria API. We'll explore how to use Hibernate and JPA to build Criteria Queries.
Criteria in Hibernate can be used for join queries by joining multiple tables, useful methods for Hibernate criteria join are createAlias(), setFetchMode() and setProjection() Criteria in Hibernate API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.
In Hibernate, the Criteria API helps us build criteria query objects dynamically. Criteria is a another technique of data retrieval apart from HQL and native SQL queries. The primary advantage of the Criteria API is that it is intuitively designed to manipulate data without using any hard-coded SQL statements.
public List<Place> findPlaces(String name, String streetname){
Criteria crit = getSession().createCriteria(Place.class, "place");
criteria.createAlias("streets", "s"); // Create alias for streets
crit.add(Restrictions.like("s.name", name+"%"));
// continue method
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With