findAll UUID MongoRepository - java

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>.

Related

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. :(

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)

How to Query MongoDB With HashMaps value Using Morphia?

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();

Hibernate restriction + projection org.hibernate.QueryException: could not resolve property

when applying a restriction to a field in a projection I'm having the following exception:
org.hibernate.QueryException: could not resolve property: surcursal of: com.adm_colas.model.AnalisisColas
at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:83)
at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:77)
at org.hibernate.persister.entity.AbstractEntityPersister.toType(AbstractEntityPersister.java:1978)
at org.hibernate.loader.criteria.EntityCriteriaInfoProvider.getType(EntityCriteriaInfoProvider.java:57)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getPathInfo(CriteriaQueryTranslator.java:245)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.createCriteriaEntityNameMap(CriteriaQueryTranslator.java:229)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.(CriteriaQueryTranslator.java:112)
at org.hibernate.loader.criteria.CriteriaLoader.(CriteriaLoader.java:88)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1663)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:380)
at org.hibernate.internal.CriteriaImpl.uniqueResult(CriteriaImpl.java:402)
at com.adm_colas.dao.AnalisisColasDAOImpl.getSumGroupBy(AnalisisColasDAOImpl.java:121)
This is the class I'm querying:
#Entity
#Table(name = "analisis_colas", catalog = "colas")
public class AnalisisColas implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private Date fecha;
private Sucursales sucursal;
private String dia;
private Double semana;
private Integer mes;
private String turno;
private Turnos turnoSucursal;
private Timestamp horaDesde;
private Double tasaEntrada;
private Double clientesNoAtendidos;
private Double tasaServicio;
private Date tiempoEsperaPromedio;
private Timestamp tiempoServicioPromedio;
private Timestamp tiempoTotalPromedio;
private Double tiempoTotalPromedioDec;
private Timestamp maximoTiempoEspera;
private Timestamp maximoTiempoServicio;
private Timestamp horaHasta;
private Double utilizacion;
private Double probSistemaVacio;
private Double probabilidadClienteEsper;
private Double nivelServicioActual;
And this is the code which is cracking my head:
public List<AnalisisColas> getGroupBy(AnalisisColas a) {
Session session = this.sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(AnalisisColas.class);
criteria.setProjection(
Projections
.projectionList()
.add(Projections.groupProperty("sucursal"), "sucursal")
.add(Projections.groupProperty("dia"), "dia")
.add(Projections.groupProperty("semana"), "semana")
.add(Projections.groupProperty("mes"), "mes")
.add(Projections.groupProperty("turnoSucursal"),
"turnoSucursal")
.add(Projections.avg("tasaEntrada"), "tasaEntrada")
.add(Projections.avg("tasaServicio"), "tasaServicio"))
.setResultTransformer(
Transformers.aliasToBean(AnalisisColas.class));
if (a.getSucursal() != null) {
criteria.createAlias("surcursal", "s").add(
Restrictions.like("s.nombre", a.getSucursal().getNombre()));
}
if (a.getMes() != null) {
criteria.add(Restrictions.eq("mes", a.getMes()));
}
if (a.getSemana() != null) {
criteria.add(Restrictions.eq("semana", a.getSemana()));
}
if (a.getDia() != null) {
criteria.add(Restrictions.eq("dia", a.getDia()));
}
if (a.getTurnoSucursal() != null) {
criteria.createAlias("turnoSucursal", "ts").add(
Restrictions.eq("ts.turnoId", a.getTurnoSucursal()
.getTurnoId()));
}
List<AnalisisColas> analisisColasList = criteria.list();
return analisisColasList;
}
Any ideas will be appreciated.
Not sure about the Spanish names, i.e. about the meaning.. but Hibernate message is pretty clear:
could not resolve property: surcursal of: com.adm_colas.model.AnalisisColas
See the word surcursal, mostly the beginning sur...
While your entity is
public class AnalisisColas implements java.io.Serializable {
...
private Sucursales sucursal;
The name is: sucursal, mostly the beginning suc...
So, this part of the query is wrong:
if (a.getSucursal() != null) {
// here SUR... instead of SUC...
criteria.createAlias("surcursal", "s").add(
Restrictions.like("s.nombre", a.getSucursal().getNombre()));

How to access Object.field in criteria in Hibernate

i have write the criteria for company class.
below are company class, companySearch class and criteria. But criteria list is throw exception. exception is "org.hibernate.QueryException: could not resolve property: san.san of: com.sesami.common.domain.Company". How to access Company.san.san?
Company class
public class Company extends DomainObject implements UserDetails {
private Long id;
private String companyName;
private CompanyType companyType;
private String description;
private String companyURL;
private String billToEmail;
private String hashPassword;
private SAN san;
#OneToOne(cascade = { CascadeType.ALL })
public SAN getSan() {
return san;
}
public void setSan(SAN san) {
this.san = san;
}
...
}
CompanySearch
public class CompanySearch {
private String companyName;
private String email;
private Long san;
private String gstNumber;
......
public Long getSan() {
return san;
}
public void setSan(Long san) {
this.san = san;
}
...
}
Criteria
companyCriteria = this.getSession().createCriteria(
Company.class);
if (companySearch.getSan() != null
&& !"".equals(companySearch.getSan()))
companyCriteria.add(Restrictions.eq("san.san",
companySearch.getSan()));
Integer count = ((Long) companyCriteria.setProjection(
Projections.rowCount()).uniqueResult()).intValue();
companyCriteria.setProjection(null);
companyCriteria.setResultTransformer(Criteria.ROOT_ENTITY);
companyCriteria
.setFirstResult((pager.getPage() - 1) * pager.getPageSize())
.setMaxResults(pager.getPageSize()).list();
List<Company> companies = companyCriteria.list();
PagedResultSet pr = new PagedResultSet();
pr.setPager(pager);
pr.setResultSet(companies);
pr.setRowCount(count);
return pr;
You must create a join to the San entity, using a subcriteria, or an alias:
companyCriteria.createAlias("san", "sanAlias");
companyCriteria.add(Restrictions.eq("sanAlias.san",
companySearch.getSan()));
or
companyCriteria.createCriteria("san").add(Restrictions.eq("san",
companySearch.getSan()));
This is well explained in the Hibernate reference documentation and even in the Criteria javadoc.
Note that this has absolutely nothing to do with Spring, and everything to do with Hibernate. If you searched in the Spring doc for how to do this, no wonder you didn't find anything.

Categories