Multiple Criteria Where in Spring Data MongoDb - mongodb

I want using #Query in Spring Data Mongodb
What is an equal for Spring Data MongoDb Query to this method?
I want to make a method to search based on the field and value that send by the someone when invoked method.
public List < Party > retrivePartyByQuery(Map<String, String> payload) {
Query query = new Query();
Iterator<Map.Entry<String, String>> iterator = payload.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
List < Party > productDb = mongoTemplate.find(query,Party.class);
return productDb;
}
}
#Query(value = "{ 'field': 'value'}")
List<Admission> findByFieldAdmission(#Param("field")String field, #Param("value") String value);```

Related

spring boot not able to retrieve gridfs

So I have been trying for hours or even the whole day on how to retrieve my gridfs from the mongodb.
This is how I save it:
DBObject dbObject = new BasicDBObject();
Map<String, Boolean> values = new HashMap<>();
values.put("boolean", true);
dbObject.put("tags", tags);
dbObject.put("description", des);
Object id = gridFsTemplate.store(file.getInputStream(), String.valueOf(file.getName()), dbObject);
Query query = new Query();
query.addCriteria(Criteria.where("email").is(jwt.extractEmail(token)));
Update update = new Update();
if(repository.findByEmail(jwt.extractEmail(token)) == null){
update.set("gridFsId", Arrays.asList(id.toString()));
}
else{
User user = repository.findByEmail(jwt.extractEmail(token));
List<String> gridFsId = user.gridFsId;
gridFsId.add(id.toString());
update.set("gridFsId", gridFsId);
}
template.updateMulti(query, update, User.class);
values.put("boolean", true);
return values;
and this is how I try to get it:
public List<item> get_items(String token){
User user = repository.findByEmail(jwt.extractEmail(token));
List<GridFSFile> items = new ArrayList<>();
}
for some reason whenever I try to use GridFSDBFile the whole line is read.
Please help ;)

Get multiple list grouped by different fields

I'm using this method to send multiple list to client.
public ResponseEntity<?> getFiveLastRequestOfEachVehicleType() {
ResponseContent content = getResponseContent();
Map<String, List<Request>> map = new HashMap<>();
GroupBy groupBy = new GroupBy();
groupBy.initialDocument("vehicleTypeEnum");
query = new Query();
queryFieldsFilterLastFiveRequest(query, VehicleTypeEnum.NEISAN);
map.put("NEISAN", mongoOperations.find(query, Request.class));
query = new Query();
queryFieldsFilterLastFiveRequest(query, VehicleTypeEnum.BADSAN);
map.put("BADSAN", mongoOperations.find(query, Request.class));
query = new Query();
queryFieldsFilterLastFiveRequest(query, VehicleTypeEnum.BUJE);
map.put("BUJE", mongoOperations.find(query, Request.class));
content.setData(map);
return getReturn(content);
}
And this method apply criteria to each query
private void queryFieldsFilterLastFiveRequest(Query query, VehicleTypeEnum vehicleTypeEnum) {
query.addCriteria(Criteria.where("vehicleTypeEnum").is(vehicleTypeEnum));
query.addCriteria(Criteria.where("unlock").is(true));
query.fields()
.include("id")
.include("goodsTypeTitle")
.include("originCityTitle")
.include("price");
query.limit(5);
}
I wonder if there is any way to retrieve all list in one request to database using MongoOperations.
I would go to grouping manually later on, first query for all vehicleType :
private void queryFieldsFilterLastFiveRequest(Query query, VehicleTypeEnum... vehicleTypeEnum..) {
query.addCriteria(Criteria.where("vehicleTypeEnum").in(vehicleTypeEnum));
query.addCriteria(Criteria.where("unlock").is(true));
query.fields()
.include("id")
.include("goodsTypeTitle")
.include("originCityTitle")
.include("price");
query.limit(5);
}
Here the is has been changed by in, and accept a list of VehicleTypeEnum
Then to use it :
public ResponseEntity<?> getFiveLastRequestOfEachVehicleType() {
ResponseContent content = getResponseContent();
Map<String, List<Request>> map;
query = new Query();
queryFieldsFilterLastFiveRequest(query, VehicleTypeEnum.NEISAN, VehicleTypeEnum.BADSAN, VehicleTypeEnum.BUJE);
map = mongoOperations.find(query, Request.class).stream()
.collect(Collectors.toMap(r -> r.getVehicleTypeEnum().name(),r -> r));
content.setData(map);
return getReturn(content);
}
Here i use the stream api to group result by VehiculeTypeEnum name

How to get table metadata from camel-sql component

I'm looking for a way to get all the column meta data for the given table name using camel-sql component.
Though it uses spring-jdbc behind the scenes i do not see a way to get the ResultSetMetaData.
I couldn't find a direct way to get the column details from camel-sql component, For now managed to get the information using spring jdbc template and data source.
public List<String> getColumnNamesFromTable(final TableData tableData) throws MetaDataAccessException {
final List<String> columnNames = new ArrayList<String>();
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
StringBuilder query = new StringBuilder();
query.append("SELECT * FROM ").append(SINGLE_BLANK_SPACE);
query.append(tableData.getSchemaName());
query.append(tableData.getTableName()).append(SINGLE_BLANK_SPACE);
query.append("WHERE rownum < 0");
jdbcTemplate.query(query.toString(), new ResultSetExtractor<Integer>() {
#Override
public Integer extractData(ResultSet rs) throws SQLException, DataAccessException {
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
columnNames.add(rsmd.getColumnName(i).toUpperCase());
}
return columnCount;
}
});
return columnNames;
}

How to return HashMap from JPA query?

I want to return a HashMap from JPA query like the below but I don't know how to fill the HashMap from this query. Actually I want to fill charts from HashMap in the frontend
public HashMap<String,String> getCount(Date start,Date end) {
HashMap<String, String> map=new HashMap<String, String>();
Query q =
em.createQuery(
"select count(i.uuid),i.username from Information i where i.entereddt between :start and :end group by i.username");
q.setParameter("start",new Timestamp(start.getTime()));
q.setParameter("end",new Timestamp(end.getTime()));
System.out.println(" query"+ q.getResultList().get(0).toString());
return map;
}
Any suggestions?
It appears that you were trying to execute a query which return types not mapped to any Java entities you have (or if they be present you never mentioned them). In this case, you want to use createNativeQuery(), which will return a List of type Object[].
Try using this version of the method:
public HashMap<String,String> getCount(Date start,Date end) {
HashMap<String, String> map=new HashMap<String, String>();
Query q = em.createNativeQuery(
"select count(i.uuid),i.username from Information i" +
"where i.entereddt between :start and :end group by i.username");
q.setParameter("start",new Timestamp(start.getTime()));
q.setParameter("end",new Timestamp(end.getTime()));
List<Object[]> list = query.getResultList();
for (Object[] result : list) {
map.put(result[0].toString(), result[1].toString());
}
return map;
}
Please refer, JPA 2.0 native query results as map
In your case in Postgres, it would be something like,
List<String> list = em.createNativeQuery("select cast(json_object_agg(count(i.uuid),i.username) as text) from schema.information i where i.entereddt between :start and :end group by i.username")
.setParameter("start",new Timestamp(start.getTime()))
.setParameter("end",new Timestamp(end.getTime()))
.getResultList();
//handle exception here, this is just sample
Map map = new ObjectMapper().readValue(list.get(0), Map.class);
Kindly note, I am just sharing my workaround with Postgres.
I know that it's an old question, but you can create an object to store info
public class UserCount {
private String username;
private Long count;
public UserCount(String user, Long count){
this.username = user;
this.count = count;
}
}
It's important to create the constructor and to pass the parameters in the correct way.
The JPQL became
select my.package.UserCount(i.username, count(i.uuid) ) from schema.information i where i.entereddt between :start and :end group by i.username
The query returns a List<UserCount> .

how could i use JPA criteria query api for joined columns?

i am new to JPA and i have a problem with it.
suppose that we have two tables which are related
by a ManytoOne association, which means that
table A stores a primary key of table B within it.
when these two tables are mapped to JPA entities
i have a problem for search on this situation.
i have used an existing code from richfaces demo, to handle filtering and sorting by using
JPA. this code is using input parameters to create criteria query.
this is the code:
private CriteriaQuery<T> createSelectCriteriaQuery() {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(entityClass);
Root<T> root = criteriaQuery.from(entityClass);
if (arrangeableState != null) {
List<Order> orders = createOrders(criteriaBuilder, root);
if (!orders.isEmpty()) {
criteriaQuery.orderBy(orders);
}
Expression<Boolean> filterCriteria = createFilterCriteria(criteriaBuilder, root);
if (filterCriteria != null) {
criteriaQuery.where(filterCriteria);
}
}
return criteriaQuery;
}
protected Expression<Boolean> createFilterCriteriaForField(String propertyName, Object filterValue, Root<T> root, CriteriaBuilder criteriaBuilder) {
String stringFilterValue = (String) filterValue;
if (Strings.isNullOrEmpty(stringFilterValue)) {
return null;
}
stringFilterValue = stringFilterValue.toLowerCase(arrangeableState.getLocale());
Path<String> expression = root.get(propertyName);
Expression<Integer> locator = criteriaBuilder.locate(criteriaBuilder.lower(expression), stringFilterValue, 1);
return criteriaBuilder.gt(locator, 0);
}
private Expression<Boolean> createFilterCriteria(CriteriaBuilder criteriaBuilder, Root<T> root) {
Expression<Boolean> filterCriteria = null;
List<FilterField> filterFields = arrangeableState.getFilterFields();
if (filterFields != null && !filterFields.isEmpty()) {
FacesContext facesContext = FacesContext.getCurrentInstance();
for (FilterField filterField : filterFields) {
String propertyName = (String) filterField.getFilterExpression().getValue(facesContext.getELContext());
Object filterValue = filterField.getFilterValue();
Expression<Boolean> predicate = createFilterCriteriaForField(propertyName, filterValue, root, criteriaBuilder);
if (predicate == null) {
continue;
}
if (filterCriteria == null) {
filterCriteria = predicate.as(Boolean.class);
} else {
filterCriteria = criteriaBuilder.and(filterCriteria, predicate.as(Boolean.class));
}
}
}
return filterCriteria;
}
the code is okay, when i try to filter columns(not joined columns), but when i try to
query on joined column, the produced query is not correct and it throws exception.
so my question is that, how could i use JPA criteria query api, to filter rows by both
joined columns and non-joined coulmns.
thanks
I don't believe you can treat join columns like regular ones.
for example if you want to filter on id of B, you would have to create a join from A to B , then use B_.id to match values.
Shay