How to Query MongoDB With HashMaps value Using Morphia? - java

This is a part of my code :
#Entity("messages")
public class Message implements Serializable {
#Id
private ObjectId id;
private long time;
#Reference(lazy = true)
private Payload payload;
private String serviceName;
private Map<String, String> headerMap;
private MessageStatus messageStatus = MessageStatus.ESB;
private MessageType messageType;
i need to find a document which
its headerMap contains "requestID".
the value of headerMap.get("requestID") equals "DUMDUMID".
Thank you

ds.find(Message.class).field("headerMap.requestID").equal("DUMDUMID").get();

Related

Graphql schema for nested hashmap

I have a mutation which accepts WorkspaceDTO(POJO):
public WorkspaceDTO createWorkspace(WorkspaceDTO workspaceDTO) {
Workspace workspace = workspaceMapper.toEntity(workspaceDTO);
Workspace newWorkspace = workspaceService.save(workspace);
return workspaceMapper.toDTO(newWorkspace);
}
WorkspaceDTO
public class WorkspaceDTO implements Serializable {
private String key;
private Map<DomainDTO, Map<String, Map<String, EntityDTO>>> entities;
}
public enum DomainDTO {
DOMAIN_BUILDER
}
public class EntityDTO {
private String key;
private String id;
private EntityNumberDTO entityNumber;
private String defPackageKey;
}
public enum EntityNumberDTO {
Entity(243L),
Entity_VERSION(244L);
private final Long id;
}
GraphQLSchema
createWorkspace(newWorkspace: WorkspaceInput!): Workspace!
input WorkspaceInput{
key: String
### How to add Map<Domain, Map<String, Map<String, Entity>>>
}
How to generate graphql schema (Map<DomainDTO, Map<String, Map<String, EntityDTO>>> entities) in Workspace Input so that client can make the request.

Filter parent and child at Realm - Android

I have two classes that I mapped as RealmObject and I would like to do a query that will filter both the parent and the child.
The query will filter all the products that are greater than the passed date and inside it filter all the compras that have date greater than the passed date.
Is it possible with a query or I really need to execute the query for products and after take this List and remove the compras that I don't want ?
public class Produto extends RealmObject implements Id{
#PrimaryKey
private Long id;
#Index
#Required
private String codigoBarras;
private String nome;
private String marca;
private String categoria;
private String subCategoria;
private Double quantidade;
private String unidade;
private byte[] imagemData;
private Date dataAlteracao;
private RealmList<Compra> compras;
...
public class Compra extends RealmObject implements Id{
#PrimaryKey
private Long id;
//#LinkingObjects("compras")
private Produto produto = null;
private Double preco;
private String local;
private String mercado;
private Date data;
private Boolean liquidacao = false;
private String observacao;
private Date dataAlteracao;
...
public List<Produto> buscarProdutoEComprasPorDataAlteracao(Long dataAlteracao) {
RealmResults<Produto> results = realm.where(Produto.class)
.greaterThan("dataAlteracao", new Date(dataAlteracao))
.greaterThan("compras.dataAlteracao", new Date(dataAlteracao))
.sort("codigoBarras")
.findAll();
return realm.copyFromRealm(results);
}
//#LinkingObjects("compras")
private Produto produto = null;
You can replace this with
#LinkingObjects("compras")
private final RealmResults<Produto> isComprasOfProdutos = null;
Although if your current query doesn't work, unfortunately Realm-Java does not support SUBQUERY nor the ALL predicate, and https://github.com/realm/realm-java/issues/5730 was never added nor do I think they will ever add it, so you'll have to do this manually. :(

How to convert List<Entity> to a string?

Here is the code :
I have a entity named ClassA which consists of following attribute
#JsonProperty("rowDeleted")
private Boolean rowDeleted;
#JsonProperty("start")
private List<Start> start = null;
#JsonProperty("end")
private List<End> end = null;
#JsonProperty("rows")
private List<Row> rows = null;
And Row is another entity which consists of attributes:
#JsonProperty("cells")
private List<Cell> cells = null;
#JsonProperty("clusteringKey")
private String clusteringKey;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
And Cell is another entity:
#JsonProperty("deleted")
private Boolean deleted;
#JsonProperty("name")
private String name;
#JsonProperty("value")
private String value;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
I am getting an object of ClassA and want to convert it into another entity which is ClassB contains fields:
private String end;
private String key;
private String keyspacename;
private String partitiondeleted;
private String rowdeleted;
private String rows;
private String start;
private String tablename;
private String triggerdate;
private String triggertime;
So basically i want to convert List rows of ClassA to String rows of ClassB.
Can anyone please suggest a way to do this.
Thanks in advance
suppose you have a list of class A.
List<A> list= . . . ;
List<B> newList=list
.stream()
.map(obj-> new B()
.setKey(obj.getKey())
.setKeyspacename(//set which field of class A will be saved)
.setPartitiondeleted()
// set more fields
)
.collect(Collecters.toList());
and then serialize this newlist into String by using jakson.
I wanted a string which could represent json format so modified my toString() as per my requirement and it solved my purpose.

Java object not populated from json request for inner class

Have searched in different sites but couldn't find correct answer, hence posting this request though it could possible duplicates.sorry for that.
I am sending the below json request to my back-end service and converting to java object for processing. I can see the request body passed to my service but when i convert from json to java object , values are not populating
{
"data":{
"username":"martin",
"customerId":1234567890,
"firstName":"john",
"lastName":"smith",
"password":"p#ssrr0rd##12",
"email":"john.smith#gmail.com",
"contactNumber":"0342323443",
"department":"sports",
"location":"texas",
"status":"unlocked",
"OrderConfigs":[
{
"vpnId":"N4234554R",
"serviceId":"connectNow",
"serviceType":"WRLIP",
"ipAddress":"10.101.10.3",
"fRoute":[
"10.255.253.0/30",
" 10.255.254.0/30"
],
"timeout":1800,
"mapId":"test_map"
}
]
}
}
My Parser class have something like,
JSONObject requestJSON = new JSONObject(requestBody).getJSONObject("data");
ObjectMapper mapper = new ObjectMapper();
final String jsonData = requestJSON.toString();
OrderDTO mappedObject= mapper.readValue(jsonData , OrderDTO .class);
// I can see value coming from front-end but not populating in the mappedObject
My OrderDTO.java
#JsonInclude(value = Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true,value = {"hibernateLazyInitializer", "handler", "created"})
public class OrderDTO {
private String username;
private long customerId;
private String source;
private String firstName;
private String lastName;
private String email;
private String contactNumber;
private String password;
private String department;
private String location;
private String status;
private List<OrderConfig> OrderConfigs;
#JsonInclude(value = Include.NON_NULL)
public class OrderConfig {
private String vpnId;
private String serviceId;
private String serviceType;
private String ipAddress;
private String mapId;
private String[] fRoutes;
private Map<String, Object> attributes;
private SubConfig subConfig;
private String routeFlag;
getter/setters
.....
}
all setter/getter
}
Not sure what I'm missing here. Is this right way to do?
If your are trying to use inner class, correct way to use is to declare it static for Jackson to work with inner classes.
For reference check this
code changes made are
#JsonInclude(value = Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
static class OrderConfig {
Make sure that your json tag names match with variable names of java object
Ex : "fRoute":[
"10.255.253.0/30",
" 10.255.254.0/30"
],
private String[] fRoutes;
OrderConfigs fields will not be initialized, just modify your bean as
#JsonProperty("OrderConfigs")
private List<OrderConfig> orderConfigs;
// setter and getter as setOrderConfigs / getOrderConfigs
See my answer here. (same issue)

findAll UUID MongoRepository

I'm trying to achive a findAllByUUID using mongo-spring-boot, but with no luck.
What I have:
public interface CarMatchRepository extends MongoRepository<CarMatchEntity, String> {
List<CarMatchEntity> findAllByCarID(Iterable<UUID> ids);
CarMatchEntity findByCarID(UUID carID);
}
Function call:
public void addCarsToCollection(String id, List<UUID> carId) {
List<CarMatchEntity> entities = carMatchRepository.findAllByCarID(carId); <--- empty
}
If I call findByCarID() it retrieves correctly a single object (if exists) but using Iterable the query does not fail, but it never returns any object. Am I doing something wrong here or am I taking the wrong road for this problem?
Thanks!
Edit:
#Document(collection = "car_index")
public class CarMatchEntity implements Serializable {
#Id
private String id;
private UUID carID;
//partner data
private UUID partnerID;
private String partnerThumbURL;
private String partnerName;
private Date partnerMembershipSince;
// car location
private List<Double> location;
private String district;
private String city;
// car data
private CarType carType;
private String carBrand;
private String carModel;
private String carPlate;
private List<CarFeature> carFeatures;
private String carAddress;
private String description;
private BigDecimal hourFare;
private BigDecimal dayFare;
private BigDecimal weekFare;
private BigDecimal dailyPrice;
private BigDecimal suggestedHourlyPrice;
private BigDecimal suggestedDailyPrice;
private BigDecimal suggestedWeeklyPrice;
private String carThumbURL;
private Map<String, CarPhotos> carPhotosURL;
private CarAvailability availability;
private CarStatus carStatus;
private String carYear;
private FuelType fuelType;
#Transient
private DayOfWeek prohibitedDay;
private String carYearModel;
#Transient
private double partnerRating = 5.0;
private CarTransmission carTransmission;
private CarColor carColor;
private String odometer;
private Integer manufactureYear;
private String fipeCode;
private String renavam;
private String chassi;
private InsuranceCompany insuranceCompany;
private List<CarSpecialFeature> carSpecialFeatures;
private BigDecimal deductible;
private Boolean superCar;
public CarMatchEntity() {
}
Try using JSON based queries with SpEL expressions
#Query("{carID: { $in: ?0 } })")
List<CarMatchEntity> findAllByCarIds(List<UUID> ids);
Use
List<CarMatchEntity> findAllByCarIDIn(Iterable<UUID> ids);
instead of
List<CarMatchEntity> findAllByCarID(Iterable<UUID> ids);
UPDATE:
Did you try to explicitly declare JPQL query instead of relying on Spring Data query generation mechanism?
#Query("select e from CarMatchEntity e where e.carID in (:ids)")
List<CarMatchEntity> findAllByCarID(#Param("ids") Iterable<UUID> ids);
UPDATE 2:
Another solution I would try is to declare argument ids in findAllByCarIDIn method as Collection<UUID> instead of Iterable<UUID>.

Categories