Springboot query criteria : mongodb - spring-boot

I have list of filtered Id as following:
filteredId=[5,44,221,34,111...]
and class Device.java:
#NotBlank
private String applicationId;
// #NotBlank
private String deviceTypeId;
#NotBlank
private String uid;
#NotBlank
private String name;
private String userId;
private String nodeId;
private String externalId;
private String softwareReleaseId;
private boolean enabled = CoreConstant.DEFAULT_ENABLED;
private boolean nameOverridden = KronosConstants.NAME_OVERRIDDEN_DEFAULT;
private Map<String, String> info = new HashMap<>();
//Getter Setter
I want to fetch all Devices which have deviceTypeId equals filteredId
I am doing something like this:
Query query = new Query();
for (int i = 0; i < filteredId.size(); i++) {
query.addCriteria(Criteria.where(filteredId.get(i)).is(device.getId()));
}
return this.MongoOperations.find(query, Device.class);
Can anyone help me with what changes I need?

try
List<Integer> filteredId = List.of(5,44,221,34,111);
Criteria criteria = Criteria.where("deviceTypeId").in(filteredId);
return mongoOperations.find(Query.query(criteria), Device.class);

Related

Sprint error querying embedded documents in mongoDB

I have a
#Data
#Document(collection = "req_language")
public class Language implements ChangeDto {
#Id
private String id = UUID.randomUUID().toString();
private String name;
private String code;
private Boolean active = Boolean.TRUE;
private Boolean deleted = Boolean.FALSE;
private Date changeAt = Date.from(Instant.now());
private String changedBy;
private String correlationId = UUID.randomUUID().toString();
}
And
#Data
#Document(collection = "req_locale")
public class Locale implements ChangeDto {
#Id
private String id = UUID.randomUUID().toString();
private String description;
private Language language;
private String code;
private String fatherCode;
private Boolean active = Boolean.TRUE;
private Boolean deleted = Boolean.FALSE;
private Date changedAt = Date.from(Instant.now());
private String changedBy;
private String correlationId = UUID.randomUUID().toString();
}
With a simple repository
#Repository
#JaversSpringDataAuditable
public interface LocalesRepository extends MongoRepository<Locale, String>, LocalesCustom {
List<Locale> findByCode(String code);
}
If a try to use the findByCode, I receive this error:
No converter found capable of converting from type [java.lang.String] to type [XXX.Language]
When I try to use query in the LocalesCustom, for example (empty)
Query query = new Query();
List<Locale> localeList = mongoTemplate.find(query, Locale.class);
Same error
I have tried #DBRef in Language, and popped others errors (I couldn't query by the language code, query.addCriteria(Criteria.where("language.code")) in LocalesRepository.
There's a right way to do it?

Spring Query annotation

I've got problem with Spring #Query annotation. It returns me nothing from postgresql despite of that there are a lot of records. I suppose that it is because of the fact that in db is eg. section_id instead of section column.
From method bellow I have all data.
#Query("select p.id, p.dataContentType, p.changeDate, p.name, p.section.id, p.line.id, p.type.id, "
+ "p.status.id, p.changeUser.id, p.insertDate, p.deletedDate, p.recNum, p.actual, p.previous.id, p.thumbnail "
+ "from Picture p where p.actual=true")
Page<Object[]> findAllWithoutData(Pageable pageable);
However I need method like bellow which returns me Picture:
#Query("select new Picture(p.id, p.dataContentType, p.changeDate, p.name, p.section, p.line, p.type, "
+ "p.status, p.changeUser, p.insertDate, p.deletedDate, p.recNum, p.actual, p.previous, p.thumbnail) "
+ "from Picture p where p.actual=true")
Page<Picture> findAllWithoutData(Pageable pageable);
Here's my entity:
public class Picture implements Serializable {
private Long id;
private byte[] data;
private String dataContentType;
private ZonedDateTime changeDate;
private String name;
private Section section;
private Line line;
private DictionaryValue type;
private DictionaryValue status;
private User changeUser;
private ZonedDateTime insertDate;
private ZonedDateTime deletedDate;
private Long recNum;
private Boolean actual;
private Picture previous;
private byte[] thumbnail;
public Picture(Long id, String dataContentType, ZonedDateTime changeDate, String name, Section section,
Line line, DictionaryValue type, DictionaryValue status, User changeUser, ZonedDateTime insertDate,
ZonedDateTime deletedDate, Long recNum, Boolean actual, Picture previous, byte[] thumbnail) {
this.id = id;
this.dataContentType = dataContentType;
this.changeDate = changeDate;
this.name = name;
this.section = section;
this.line = line;
this.type = type;
this.status = status;
this.changeUser = changeUser;
this.insertDate = insertDate;
this.deletedDate = deletedDate;
this.recNum = recNum;
this.actual = actual;
this.previous = previous;
this.thumbnail = thumbnail;
}
Try something like :
#Query("select p from Picture p where p.actual=true")
Page<Picture> findAllWithoutData(Pageable pageable);
Also, you will need to keep an empty constructor to your entity.

Spring data mongoDB: Get the distinct rows with pagination

I have User class like,
#Document(collection = "users")
public class User {
private String id;
private String firstName;
private String lastName;
private String jobTitle;
private String email;
private String phoneNumber;
}
And UserDimension as,
#Document(collection = "userDimensions")
public class UserDimension{
private String id;
private String userId;
private String dimensionId;
private String status;
}
I want the userDimension records from mongoDB based on distinct userId with pagination in spring data mongoDB ?
I am using the query like,
Query query = new Query();
List<UserDimension> userDimensionList = null;
// apply pagination parameters to the search criteria
query.with(pageable);
userDimensionList = mongoTemplate.getCollection("userDimensions").distinct("userId", query.getQueryObject());
But it still giving me the total records.

#Id generated value in monogdb spring mvc

I am trying to generate different id for my db but it keep generate 0 and delete the old record how can i generate id in this code knowing that i need the id to be int for front end angular service .
#Document(collection = "tasks")
public class Task {
#Id
#Field(value = "task_id")
private int id;
#Field(value = "task_name")
private String taskName;
#Field(value = "task_description")
private String taskDescription;
#Field(value = "task_priority")
private String taskPriority;
#Field(value = "task_status")
private String taskStatus;
#Field(value = "task_archived")
private int taskArchived = 0;
//set and get
}
i found two ways to do it first one
private static final AtomicInteger counter = new AtomicInteger();
public static int nextValue() {
return counter.getAndIncrement();
}
/*******************/
#Id
#Field(value = "task_id")
private int id = nextValue();
second one i consider it a trick is to use current Date as an integer
private int id = (int) (new Date().getTime()/1000);
The simplest way is two generate unique ID with one of method provided by Java
UUID ( Universal Unique ID)
SecureRandom and MessageDigest
UID
Atomic Integer increments (that is what you need)
And many other methods
Depending on your needs pick the most suitible one. Here is a method with AtomicInteger which solves your issue :
#Document(collection = "tasks")
public class Task {
#Id
#Field(value = "task_id")
private int id;
#Field(value = "task_name")
private String taskName;
#Field(value = "task_description")
private String taskDescription;
#Field(value = "task_priority")
private String taskPriority;
#Field(value = "task_status")
private String taskStatus;
#Field(value = "task_archived")
private int taskArchived = 0;
#Transient
private AtomicInteger incrementor = new AtomicInteger(0);
public Task() {
id = incrementor.incrementAndGet(0);
}
//set and get
}
Also you have to use #Transient to avoid the incrementor being persisted in the document store.

how to use spring data neo4j search for fulltext

I am learning spring data neo4j and spring .I want to search fulltext,for example I have three Movies (sky,sky1,sky2),when i search "sky",it return sky,sky1,sky2.firt i use repository below
package com.oberon.fm.repository;
#Repository
public interface MovieRepository extends GraphRepository<Movie> {
Movie findById(String id);
Page<Movie> findByTitleLike(String title, Pageable page);
}
My controller below
#RequestMapping(value = "/movies", method = RequestMethod.GET, headers = "Accept=text/html")
public String findMovies(Model model, #RequestParam("q") String query) {
log.debug("1");
if (query != null && !query.isEmpty()) {
Page<Movie> movies =movieRepository.findByTitleLike(query, new PageRequest(0, 20));
model.addAttribute("movies", movies.getContent());
} else {
model.addAttribute("movies", Collections.emptyList());
}
model.addAttribute("query", query);
addUser(model);
return "/movies/list";
}
these does not work well,i think somewhere might be wrong,but i dont know,if you have any idea,tell me thanks! by the way,it throw exception java.lang.NullPointerException.
My Movie entity
#NodeEntity
public class Movie {
#GraphId
Long nodeId;
#Indexed(indexType = IndexType.FULLTEXT, indexName = "id")
String id;
#Indexed(indexType = IndexType.FULLTEXT, indexName = "search")
String title;
String description;
#RelatedTo(type = "DIRECTED", direction = INCOMING)
Set<Director> directors;
#RelatedTo(type = "ACTS_IN", direction = INCOMING)
Set<Actor> actors;
#RelatedToVia(type = "ACTS_IN", direction = INCOMING)
Iterable<Role> roles;
#RelatedToVia(type = "RATED", direction = INCOMING)
#Fetch
Iterable<Rating> ratings;
private String language;
private String imdbId;
private String tagline;
private Date releaseDate;
private Integer runtime;
private String homepage;
private String trailer;
private String genre;
private String studio;
private Integer version;
private Date lastModified;
private String imageUrl;

Resources