I am creating a REST service using springboot and MONGO as database.
I have a StudentDTO class with the following fields :
Class StudentDTO{
#Id
int s_no;
String name;
String dept;
int dept_no;
String course;
//getter and setters
}
I have some criteria on which i need to fetch the data. These criteria may vary. Below are some example :
1. Can fetch data on name, dept
2. Can fetch data on name, id
3. May want data on name, dept and course. etc
There is no fixed combination of criteria on which I can build my query.
One of the solution which is not appropriate i try to write is :
Query query = new Query();
Criteria criteria = new Criteria().andOperator(
Criteria.where("id").is(Integer.parseInt(dto.getId()),
Criteria.where("name").is(dto.getName()),
Criteria.where("dept").exists(true).is(dto.getDept()),
Criteria.where("dept_no").is(dto.getDept_no()),
Criteria.where("course").is(dto.getSource()));
query.addCriteria(criteria);
List<StudentDTO> recordsList = mongoTemplate.find(query, StudentDTO.class, "student_collection");
In the above solution there is no accommodation for the scenario is any of the field is missing.
To check weather attribute exist or not i tried using the below query :
Criteria.where("id").exist(true).is(Integer.parseInt(dto.getId());
but how i can add criteria over the DTO fields.
You can use below code. Use orOperator which accepts the array of criteria. Prepare the criteria values dynamically inside if statements and add the criteria array to or criteria.
Query query = new Query();
Criteria criteria = new Criteria();
List<Criteria> orCriterias = new ArrayList<>();
if( dto.getId() != null) {
orCriterias.add(Criteria.where("id").is(Integer.parseInt(dto.getId())));
}
... so on for other fields
criteria.orOperator(orCriterias.toArray(new Criteria[orCriterias.size()]));
query.addCriteria(criteria);
List<StudentDTO> recordsList = mongoTemplate.find(query, StudentDTO.class, "student_collection");
Related
I have a Student entity and want to select only two fields - id and age. After reading different posts I wrote the following code:
CriteriaQuery<Student> criteriaQuery = ..
var root = criteriaQuery.from(Student.class);
criteriaQuery.multiselect(root.get("id"), root.get("age"));
typedQuery = entityManager.createQuery(criteriaQuery);
List<Student> students = typedQuery.getResultList();
However, it doesn't work. How to do it using hibernate jpa provider?
If you only want two fields and use multiselect you can use a TupleQuery like in the example below:
CriteriaQuery<Tuple> criteriaQuery = criteriaBuilder.createTupleQuery();
var root = criteriaQuery.from(Student.class);
criteriaQuery.multiselect(root.get("id"), root.get("age"));
typedQuery = entityManager.createQuery(criteriaQuery);
List<Tuple> students = typedQuery.getResultList();
To access the values of the tuples use the get method of it.
E.g.:
Long id = (Long) students.get(0).get(0);
I want to get lists of data Review where reviewer object has id = "mawar_merah2".
How to create a query using MongoTemplate in spring boot.
this is my query:
Query query = new Query();
query.addCriteria(Criteria.where("reviewer").elemMatch(Criteria.where("id").is("mawar_merah2")));
List<Review> timeLinesReview = getMongoTemplate().find(query, Review.class);
return timeLinesReview;
Just use reviewer.id in query
Change
query.addCriteria(Criteria.where("reviewer").elemMatch(Criteria.where("id").is("mawar_merah2")));
To
query.addCriteria(Criteria.where("reviewer.id").is("mawar_merah2")));
I am trying to join multiple tables and to map the table columns to list of user objects.
Below is the SQL query and I am trying to convert to ORM using Hibernate Criteria:
SELECT table1.domainname, table2.policyname,table3.filterpath,table4.userdirectoryname
FROM table1, table2,table3, table4
WHERE table3.domainoid = table1.domainoid
AND table3.policyoid = table2.policyoid
AND table3.userdirectoryoid = table4.userdirectoryoid
AND table1.domainname = 'admin'
From the above query, we will get a list of user objects and trying to map the results to the user object. Below is the POJO class of the user object to form.
public class DomainDetails {
String domainName, policyName, filterPath, userDirName;
public DomainDetails(String domainName, String policyName, String filterPath, String userDirName) {
super();
this.domainName = domainName;
this.policyName = policyName;
this.filterPath = filterPath;
this.userDirName = userDirName;
}
// getters and setters...
}
How to join the multiple tables and the mapping of the respective columns to the user object?
appreciate the help..thanks
You can use mapping annotation ..
Mapping entity associations/relationships
I have entity DataStatus with the field date.
My goal is get the oldest row by date field.
public DataStatus getOldest(){
Criteria criteria = session.createCriteria(DataStatus.class);
criteria.add(Restrictions.eq("date", MIN));
List<DataStatus> results = criteria.list();
if(results.size()<1)return null;
return results.get(0);
}
User order by mechanism from criteria API
CriteriaQuery<DataStatus> q = cb.createQuery(DataStatus.class);
Root<DataStatus> c = q.from(DataStatus.class);
q.select(c);
q.orderBy(cb.asc(c.get("date")));
Usually I use hibernate session.get(Class.class,id) to get entity class.
here in get method I gave 2nd arg as id value (i.e int id=7)
My question is how to use non id value in hibernate session.get(Class.class,non_id), I need to get values with some other column (non id column).
You can use Criteria Queries. So in your case maybe like this:
Criteria crit = session.createCriteria(Class.class);
crit.add(Restrictions.eq("non_id", "myNonIdValue"));
List results = crit.list();
Class myClassObj = (myClassObj) results.get(0);
You can't do a get with a non-id. You will have to query for the object you need, like you would in SQL.
String queryText = "from SomeObject where objectPropery = :VALUE"
Query queryObj = session.createQuery( queryText );
queryObj.setParameter( "VALUE", value );
return queryObj.uniqueResult()
You can read all about queryObjects here: Query
If you are querying for objects, you will have to get to know HQL.
You can use Hibernate with JPA 2
class MyClass { #Id long id; #Basic String description; }
TypedQuery<MyClass> query =
getEntityManager().createNamedQuery("select myClass from MyClass where description = :description", MyClass.class);
query.setParameter("description", "example");
List<MyClass> myClasses = query.getResultList();
Or a single entity:
MyClass myClass = query.getSingleResult();