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
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
}
Related
We have entity:
Class Drink {
Long id;
String name;
List "Integer" ingredients; // We store ingredient's numbers in this list
}
For example: id = 1, name = Mojito, ingredients = {5,7,3,8}
Let's say, i want to find a drink based on ingredients. How should I do that?
Retrieve all cocktails from data base and iterate through them for comparison?
Or comparison should be conducted in a data-base? If this is correct answer, How can I to that? (How to compare Lists of Integers in the DB)?
Most likely you'll want to filter the data on the database level. The exact solution depends on the type of the database structure and the framework that you use, but since you use PostgreSQL, I assume you have a relational database structure, and since you speak of an "entity", I assume you use something like Hibernate or JPA to interact with it.
Then probably your drinks should reference their ingredients not as numbers, but as entities. This is how the mapping could look like:
class Drink {
Long id;
String name;
#ManyToMany
#JoinTable(tableName = "drink_ingredients")
List<Ingredient> ingredients;
}
class Ingredient {
Long id;
String name;
}
Then a query to find all drinks containing a specific ingredient would be:
Query query = entityManager.createQuery("select d from Drink d "
+ "join d.ingredients i "
+ "where i.name = :ingredientName");
query.setParameter("ingredientName", "Lime");
List<Drink> drinks = (List<Drink>) query.getResultList();
Let's say we have a collection of "people" inside people collection we have person objects of
public class Person{
public String personId;
public String firstName;
public String lastName;
}
I want to search persons by using firstName and lastName in the same time with startAt and endAt methods like below
Query query = FirebaseFirestore.getInstance()
.collection("people").orderBy("firstName",
Query.Direction.ASCENDING).
orderBy("lastName", Query.Direction.ASCENDING).startAt(key).endAt(key + "\uf8ff");
FirestoreRecyclerOptions<Person> options = new FirestoreRecyclerOptions.Builder<Person>()
.setQuery(query, Person.class)
.build();
but I can only use either firstName or lastName how can I use both at the same time?
I'm not sure that startAt and endAt are the right things for you. Those are used for pagination, and it doesn't look like that's what you're trying to do here. If you just want to filter all people by some common first and last time, just do a normal query with where clauses to filter those names and order them as needed:
Query query = FirebaseFirestore.getInstance()
.collection("people")
.whereEqualTo("lastName", yourLastName)
.whereEqualTo("firstName", yourFirstName)
.orderBy("lastName")
.orderBy("firstName")
I have entity
User {
long id;
String firstname;
}
And I would like to have query with many firstname like:
select * from user where firstname in names;
Where names are:
List names = new ArrayList();
names.add("Kowalsky");
names.add("Smith");
How this can be done using spring jpa data meta language?
I've tried already:
List<User> findByFirstName(List<String> firstName);
but id doesnt work.
please help
This should work.
List<User> findByFirstNameIn(List<String> firstName);
You need to use In keyword when you are passing a List
In this scenario rather than doing complete select on object,have decided to go for select statement on fields required only.Hence the queries generated will be less.
Once the result is in,i want to cast back to original values and return them to calling method.
Please suggest any alternative efficient approach.
public class Student {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
#Column(name="enroll_id")
private String enrollmentId;
public Student(Integer id, String enrollmentId) {
super();
this.id = id;
this.enrollmentId = enrollmentId;
}
// source code continues
}
public List<Student> getStudentList(){
Query multipleSelect=em.createQuery("select student.id,student.enrollmentId from Student as student");
List<Object[]> studentList=multipleSelect.getResultList();
List<Student> studentArrayList=new ArrayList<Student>();
for(Object[] list:studentList){
Integer id=((Integer)list[0]);
String eId=((String)list[1]);
studentArrayList.add(new Student(id, eId));
}
return studentArrayList;
}
If you're asking for a way to avoid casting each row from the resultList and having to manually create Student object then try using "JPQL Constructor Expressions"
You're select query can be modified as:
"select NEW com.FullyQualifiedName.Student(student.id,student.enrollmentId) from Student as student"
and accept the query result directly as
List<Student> studentList=multipleSelect.getResultList();
or Simply:
public List<Student> getStudentList(){
return em.createQuery("select NEW com.FullyQualifiedName.Student(student.id,student.enrollmentId) from Student as student").getResultList();
}
Note:
Make sure Student constructor is called using fully qualified name.
Do not use JPQL with createNativeQuery.
If you want the output of the query to be of Student type then you'll have to create the query in a different way, i.e.,
TypedQuery<Student> multipleSelect=em.createQuery("select NEW your_package.Student(student.id,student.enrollmentId) from Student as student"
, Student.class);
List<Student> students = multipleSelect.getResultList();
However, this is not a good way to do this as the return type of the method would suggest that it is returning a completely filled Student object. Also, you'll have to make constructors for every combination. I would rather suggest you fetch a map, i.e.,
TypedQuery<Map> multipleSelect=em.createQuery("select NEW map(student.id as id,student.enrollmentId as eid) from Student as student"
, Map.class);
List<Map> students = multipleSelect.getResultList();
This will return you a map with key as "id" and value as the actual id of the student.
I'm using MongoRepository in my service. In my case, I have three field whose names are "Name", "Age" and "Gender". I could have following methods in my interface to query the data:
List<People> getByName(String name);
List<People> getByAge(String age);
List<People> getByNameAndGender(String name, String gender);
...and so on...
Now I want to query data with every combination of these 3 fields, so I need to write 7 (3 + 3 + 1) methods here and it is really ugly.
I tried to write something like
List<People> getByNameAndAgeAndGender(String name, String age, String gender);
And if the input has only two fields: name = Chris, age = 18, then I could call
List<People> peoples = getByNameAndAgeAndGender("Chris", "18", "*")
to get the list of people whose name is Chris and age is 18. How can I achieve this goal? I really don't want to write a big "if...else if...else if..." body. Thank you!
Try this:
List<People> getByNameLikeAndAgeLikeAndGenderLike(String name, String age, String gender);