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()));
Related
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. :(
Basically I have this table:
CREATE TABLE experiment(
experimentid varchar,
description text,
rt float,
intensity float,
mz float,
identifier text,
chemical_formula text,
filename text,
PRIMARY KEY ((experimentid),description, rt, intensity, mz, identifier, chemical_formula, filename)
);
with Experiment.java
#Table(name= "experiment")
public class Experiment implements Serializable{
#PrimaryKey
private ExperimentKey experimentKey;
public ExperimentKey getExperimentKey() {
return experimentKey;
}
public void setExperimentKey(ExperimentKey experimentKey) {
this.experimentKey = experimentKey;
}
}
and ExperimentKey.java
#PrimaryKeyClass
public class ExperimentKey implements Serializable {
#PrimaryKeyColumn(name = "experimentid",ordinal = 0,type = PrimaryKeyType.PARTITIONED)
#CassandraType(type=DataType.Name.VARCHAR)
private String experimentid;
#PrimaryKeyColumn(name = "description",ordinal = 1)
#CassandraType(type=DataType.Name.VARCHAR)
private String description;
#PrimaryKeyColumn(name = "rt",ordinal = 2)
#CassandraType(type=DataType.Name.FLOAT)
private Float rt;
#PrimaryKeyColumn(name = "intensity",ordinal = 3)
#CassandraType(type=DataType.Name.FLOAT)
private Float intensity;
#PrimaryKeyColumn(name = "mz",ordinal = 4)
#CassandraType(type=DataType.Name.FLOAT)
private Float mz;
#PrimaryKeyColumn(name = "identifier",ordinal = 5)
#CassandraType(type=DataType.Name.VARCHAR)
private String identifier;
#PrimaryKeyColumn(name = "chemical_formula",ordinal = 6)
#CassandraType(type=DataType.Name.VARCHAR)
private String chemical_formula;
#PrimaryKeyColumn(name = "filename",ordinal = 7)
#CassandraType(type=DataType.Name.VARCHAR)
private String filename;
//getters and setters
public ExperimentKey(){
}
}
and basically I want to implement the query below through crudrepository:
Delete * from experiment where experimentid='(something)';
I know I can SELECT based only on the partition key with findAllByExperimentKey_Experimentid(experimentid), but is it possible to do the same with delete?
I tried deleteAllByExperimentKey_Experimentid(experimentid) but I am getting an error:
Failed to instantiate void using constructor NO_CONSTRUCTOR with arguments
EDIT 1
Ok, so this is my ExperimentRepo.java
public interface ExperimentRepo extends CrudRepository<Experiment,ExperimentKey>{
public void deleteAllByByExperimentKey_Experimentid(String expid);
}
and this is my ExperimentServiceImpl.java
#Service
public class ExperimentServiceImpl implements ExperimentService{
private ExperimentRepo experimentRepo;
#Autowired
public ExperimentServiceImpl(ExperimentRepo experimentRepo){
this.experimentRepo=experimentRepo;
}
#Override
public void deleteAllExperimentByExperimentid(String expid){
MapId id = id("experimentid", expid);
experimentRepo.deleteAllByByExperimentKey_Experimentid(expid);
}
Not sure where I should use the MapId id = id("experimentid", < Serializable Value > ).
First of all, sorry if the subject has already been answered, but i've been searching for almost 6hours in a row, and trying everything i could find on the web, but i'm still stuck..
I Have a problem when i'm executing my code.. I can't find the origin of it, nor a solution...
Here's my different classes: (btw it's my first post on SOF, let me know if you need more information).
I'm going to post my Pojo's, useful DAO's and MySQL table creation orders, and the error message i get.
POJOs:
-Celebrite:
#Entity
#Table(name="Celebrite")
public class Celebrite implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name="numCelebrite")
#GeneratedValue(strategy=GenerationType.IDENTITY)
#JoinColumn(name="numCelebrite")
private int numCelebrite;
#Column(name="nom")
private String nom;
#Column(name="prenom")
private String prenom;
#Column(name="nationalite")
private String nationalite;
#Column(name="epoque")
private String epoque;
public Celebrite() {
super();
}
public Celebrite(String nom, String prenom, String nationalite, String epoque) {
super();
this.nom = nom;
this.prenom = prenom;
this.nationalite = nationalite;
this.epoque = epoque;
}
public int getNumCelebrite() {
return numCelebrite;
}
public void setNumCelebrite(int numCelebrite) {
this.numCelebrite = numCelebrite;
}
//Other getters/setters
}
-Monument
#Entity
public class Monument implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private String codeM;
private String nomM;
private String proprietaire;
private String typeMonument;
private float latitude;
private float longitude;
public Monument() {
super();
}
public Monument( String codeM,String nomM, String propritaire, String typeMonument, float latitude, float longitude) {
super();
this.codeM=codeM;
this.nomM = nomM;
this.proprietaire = propritaire;
this.typeMonument = typeMonument;
this.latitude = latitude;
this.longitude = longitude;
}
public Monument( String nomM, String propritaire, String typeMonument, float latitude, float longitude) {
super();
this.nomM = nomM;
this.proprietaire = propritaire;
this.typeMonument = typeMonument;
this.latitude = latitude;
this.longitude = longitude;
}
public String getCodeM() {
return codeM;
}
public void setCodeM(String codeM) {
this.codeM = codeM;
}
//other getters/setters..
}
-AssocieA (translation : AssociatedTo)
#Entity
public class AssocieA implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#ManyToOne(fetch=FetchType.LAZY,cascade=CascadeType.ALL)
#JoinColumn(name="numCelebrite",referencedColumnName="numCelebrite")
private Celebrite celebrite;
//private int numCelebrite;
#Id
#ManyToOne(fetch=FetchType.LAZY,cascade=CascadeType.ALL)
#JoinColumn(name="codeM",referencedColumnName="codeM")
//private String codeM;
private Monument monument;
public AssocieA() {
}
public AssocieA(Celebrite celebrite, Monument monument) {
super();
this.celebrite = celebrite;
this.monument = monument;
}
//getters/setters
}
Ok now the DAO, i'm only posting AssocieA's DAO as the others are working perfectly
public class DAOAssocieA {
EntityManagerFactory emf;
EntityManager em ;
public DAOAssocieA() {
super();
this.emf = Persistence.createEntityManagerFactory("jpa-societe-pu");
this.em = emf.createEntityManager();
}
public List<AssocieA> getAssociatedMonuments(int numCelebrite){
Query req=em.createQuery("Select a from AssocieA a where a.numCelebrite =" + numCelebrite);
return req.getResultList();
}
public List<AssocieA> getAssociatedCelebrities(String codeM){
Query req=em.createQuery("Select a from AssocieA a where a.codeM = '"+codeM+"'");
return req.getResultList();
}
}
Finally, the 'main' class
public String execute() {
setDAOc(new DAOCelebrite());
setDAOm(new DAOMonument());
setDAOa(new DAOAssocieA());
if (getNom()==null)
setNom("");
if (getPrenom() == null)
setPrenom("");
if (getNationalite() == null)
setNationalite("");
if (getEpoque()==null)
setEpoque("");
setListeCelebrite(DAOc.getCelebritiesBy(getNom(),getPrenom(),getNationalite(), getEpoque()));
System.out.println(getAssociated());
if (getAssociated().equals("on")) {
for (Celebrite c:listeCelebrite) {
for (AssocieA a : DAOa.getAssociatedMonuments(c.getNumCelebrite())){
System.out.println(a.getCelebrite());
System.out.println(a.getMonument());
}
}
}
return ("success");
-> The return ("success") is because i use Struts2
Now, Table creation orders (on MySQL)
CREATE TABLE Celebrite (numCelebrite int auto_increment, nom varchar(16), prenom varchar(16), nationalite varchar(10), epoque varchar(6), PRIMARY KEY (numCelebrite)) ENGINE=InnoDB;
CREATE TABLE Monument (codeM varchar(5), nomM varchar(25), proprietaire varchar(10), typeMonument varchar(16), longitude float, latitude float, PRIMARY KEY (codeM)) ENGINE=InnoDB;
CREATE TABLE AssocieA (codeM varchar(5), numCelebrite int, PRIMARY KEY (codeM,numCelebrite), FOREIGN KEY (codeM) REFERENCES Monument(codeM), FOREIGN KEY (numCelebrite) REFERENCES Celebrite(numCelebrite)) ENGINE=InnoDB;
To finish, the error message i get:
org.hibernate.QueryException: could not resolve property: numCelebrite of: pojo.AssocieA [Select a from pojo.AssocieA a where a.numCelebrite =1]
I understand that the class 'AssocieA' doesn't have a "numCelebrite" property, but i thought that because of the #ManyToOne annotation, Celebrite Table should be loaded when Associe is loaded.
Else, could you give me some tips to explain how to do that?
The final goal is: having a Celebrite, i'd like, using the numCelebrite, to retrieve every Monuments related to it, using the AssocieA table.
Thank you in advance
EDIT: Solution found on another website by kulturman:
I was using native queries:
em.createQuery("from AssocieA a where a.numCelebrite =" + numCelebrite);
Instead of JPQL (HQL queries):
em.createQuery("from AssocieA a where a.celebrite.numCelebrite =" + numCelebrite);
For those who want to see directly the solution, it's in french on OpenClassRoom
Try removing the #JoinColumn(name="numCelebrite") and #GeneratedValue(strategy=GenerationType.IDENTITY) in celebrity pojo, change CascadeType.ALL to CascadeType.Persist and let us know what happen. I'm not an expert but I think that way you can do the trick.
Solution found on another website by kulturman:
I had to replace:
em.createQuery("from AssocieA a where a.numCelebrite =" + numCelebrite);
Instead of JPQL (HQL queries):
by:
em.createQuery("from AssocieA a where a.celebrite.numCelebrite =" + numCelebrite);
Here's the explanation:
I was building my query as if i was requesting my database :
The table AssocieA has the attribute "numCelebrite"
But in my case, I mapped the tables to my classes: Each row of the AssocieA table is now an instance of my AssocieA class.
Using a HQL query, i'm requesting on the instance of my class, not the table of my database.
So what i have to do is a.getCelebrite().getNumCelebrite(), hence the "a.celebrite.numCelebrite"
I hope i've made myself clear enough because my english is not that good.
Here's the link of the forum i had this answer on (it's in french):
https://openclassrooms.com/forum/sujet/org-hibernate-queryexception?page=1#message-92165885
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>.
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.