I have 2 entities whose extracts are like these:
public class Visita {
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="pdv_uid")
private PuntoDeVenta pdv;
}
public class PuntoDeVenta {
private Integer idclient;
private String zona;
#ManyToOne
#JoinColumn(name="pdv_categoria_uid", nullable=true)
private PuntoDeVentaCategoria categoria;
}
public class PuntoDeVentaCategoria {
private String descripcion;
}
I try to do restrictions with the differents fields and some of them work, some of them don't.
With this root criteria:
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Visita.class).createAlias("pdv", "pdv");
I try to make restrictions with the differents fields of "PuntoDeVenta" and "PuntoDeVentaCategoria" (with and without the createAlias) and I get the exception "could not resolve property", for example:
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Visita.class).createAlias("pdv", "pdv").add(Restrictions.eq("pdv.categoria.descripcion", "example"));
I've researching and I didn't found anything for my case.
Thank you in advance
Related
I have this entities:
public class AnswerEntity {
#ManyToOne
private UserEntity user;
#ManyToOne
private AnswerDirectoryEntity answer;
#ManyToOne
private QuestionEntity question;
}
public class QuestionEntity {
#ManyToOne
private QuestionnaireEntity questionnaire;
}
public class QuestionnaireEntity {
private String code;
}
I need to take all user answers by user ID and corresponding code from QuestionnaireEntity.
I do it by create query like this:
List<AnswerEntity> answerList = answerRepository.findAllByUserId(userId);
and iterate over each object in my list and with using equals I compare each object to my questionnaire code:
for(AnswerEntity answerEntity : answerList){
if(answerEntity.getQuestion().getQuestionnaire().getCode().equals(questionnaireId)){
///
}
but this solution is very slow because it must iterate each object from my database,
can anybody tell my how to create an query in my repository which can help me?
You can use JPA method query this way in repository
List<AnswerEntity> findByUserIdAndQuestionQuestionnaireCode(Integer userId, String code);
I'm still new in mongodb, If I have a class like below and I want to set a property Role which is Object Type Property, how can I achieve it ? please check the class below
#Document(collection="User")
public class UserBean {
#Id
private String id;
private String userName;
private String password;
private RoleBean role;
}
#Document(collection="Role")
public class RoleBean {
#Id
private String id;
private String roleID;
private String roleName;
}
I need to set the UserBean's role property. So what is the best way to achieve it? Thanks.
Spring Mongo Template not saving the list of custom objects to MongoDb please see if this quation is already answered, or answer satisfies your requirements.
I have two objects User and House. One user can have several houses.
Annotations from House.class:
#Entity
#Table(name="house")
public class House {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="house_id")
private int id;
#ManyToOne
#JoinColumn(name="user_id")
private User user;
#Column(name="country")
private String country;
#Column(name="city")
private String city;
#Column(name="street")
private String street;
#Column(name="post_code")
private String postCode;
#Column(name="house_number")
private String houseNumber;
#Column(name="flats")
private int flats;
#Column(name="picture")
private String picture;
#Column(name="surname_first") // order names will be written in receipt
private Boolean writeSurnameFirst;
#Column(name="cut_name") // Nado ili net sokrashat imena
private Boolean cutName;
#ManyToOne
#JoinColumn(name="currency_id")
private Currency currency;
#ManyToOne
#JoinColumn(name="documentation_lang_id")
private Languages documentationLang;
#Column(name="default_house")
private Boolean defaultHouse;
I need to get a House object based on User and column defaultHouse = true.
I tried this code, but I can't get how to implement User into it:
tx = sess.beginTransaction();
// create criteria builder
CriteriaBuilder builder = sess.getCriteriaBuilder();
// create criteria
CriteriaQuery<House> query = builder.createQuery(House.class);
// specify criteria root
Root<House> root = query.from(House.class);
query.select(root).where(builder.equal(root.get("default_house"), true)
.and(builder.equal(root.get(House.getUser), user)));
house = sess.createQuery(query).getSingleResult();
tx.commit();
In fact builder.and() takes two parameters which are the two restrictions to be joined with AND keyword in SQL, and the builder.and() should be used inside builder.where() method.
change the following code:
query.select(root).where(builder.equal(root.get("default_house"), true)
.and(builder.equal(root.get(House.getUser), user)));
Like this:
query.select(root).where(builder.and(builder.equal(root.get("default_house"), true), builder.equal(root.get(House.getUser), user))));
Please refer to Hibernate ORM 5.2.11.Final User Guide for further details and more examples.
Note:
Hibernate is concerned about objects and not tables and when we use its modules like Criteria we use attributes names in the Object and not DB columns names.
In CriteriaBuilder methods you must use the entity field names like following:
builder.equal(root.get("defaultHouse"), true)
and not the database column names:
builder.equal(root.get("default_house"), true)
I attached my example:
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Eje> query = builder.createQuery(Eje.class);
Root<Eje> productRoot = query.from(Eje.class);
query.select(productRoot)
.where(builder.and(builder.equal(productRoot.get("id"), 1), builder.equal(productRoot.get(Eje_.factorCriticos).get(FactorCritico_.id), 1)));
result =(List<T>) session.createQuery(query).getResultList();
I have two classes, monitoringExpression and reportTrigger, with a one-to-many relationship. Hibernate is attempting to persist duplicate reportTriggers from the collection held by the monitoringExpression class. The first insert into the reportTrigger collection works, but subsequent inserts fail with a unique constraint violation because hibernate tries to persist the same reportTrigger twice. This is quite similar to a known hibernate bug (Hibernate inserts duplicates into a #OneToMany collection); however, in this case, we are not using a lazy collection. Here is the relevant code:
MonitoringExpression.Class
#Audited
#Entity
#Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class MonitoringExpression extends GeneratedIdXmlObject{
private String name;
private DeterminantDefinition determinantDefinition;
private String valueExpression;
private String testExpression;
private String messageExpression;
private String messageSeverity;
private boolean setExitStatusWhenTrue;
protected SortedSet<MonitoringExpressionAttribute> attributes = new TreeSet<MonitoringExpressionAttribute>();
private String color;
private Set<ReportTrigger> reportTriggers = new HashSet<ReportTrigger>();
.
.
.
#OneToMany(mappedBy="monitoringExpression",orphanRemoval=true,cascade={CascadeType.ALL},fetch=FetchType.EAGER)
#Sort(type=SortType.NATURAL)
#Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public SortedSet<MonitoringExpressionAttribute> getAttributes() {
return attributes;
}
public void setAttributes(SortedSet<MonitoringExpressionAttribute> attributes) {
this.attributes = attributes;
}
ReportTrigger.Class
#Audited
#Table(name="ReportTrigger")
#Entity
#Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class ReportTrigger extends GeneratedIdXmlObject{
private String name;
private String description;
private TriggerableReport report;
private Frequency burstPeriodSize;
private String periodStartExpression;
private String periodEndExpression;
private Set<ReportTriggerParameterMapping> parameterMappings = new HashSet<ReportTriggerParameterMapping>();
private MonitoringExpression monitoringExpression;
#XmlIDREF
#ManyToOne
#Audited
#GraphProcessorOverride(process=false,recurse=false)
#NaturalId(mutable=true)
public TriggerableReport getReport() {
return report;
}
public void setReport(TriggerableReport report) {
this.report = report;
}
#Embedded
public Frequency getBurstPeriodSize() {
return burstPeriodSize;
}
public void setBurstPeriodSize(Frequency burstPeriodSize) {
this.burstPeriodSize = burstPeriodSize;
}
#Audited
#OneToMany(mappedBy="reportTrigger",orphanRemoval=true,cascade={CascadeType.ALL})
#Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public Set<ReportTriggerParameterMapping> getParameterMappings() {
return parameterMappings;
}
.
.
.
#XmlIDREF
#ManyToOne
#GraphProcessorOverride(process=false,recurse=false)
#NaturalId(mutable=true)
public MonitoringExpression getMonitoringExpression() {
return monitoringExpression;
}
public void setMonitoringExpression(MonitoringExpression monitoringExpression) {
this.monitoringExpression = monitoringExpression;
}
As far as I can tell, we're not doing anything out of the ordinary to the reportTrigger collection (and we obviously cannot be adding the same tigger twice to a set). Has anyone seen anything like this? Thanks
Hibernate 3.6.10
Java 8
I think can do some checking as below
- Check unique constraint violation error you got is on which field ? It can be on Primary key column but also can any unique columns.
- If the violation is with your primary key then while your collection is a set then it can be 2 different TriggerableReport but share the same key value.
I have a class DocMovement like this :
#Entity
#Table(name = "DOC_MVMNT")
public class DocMovement {
#Id
#GeneratedValue
#Column(name = "MVMNT_ID")
private int mvmnt_id;
#ManyToOne
#JoinColumn(name = "BARCODE")
public DocMaster docMaster;
// other fields and getters setters
}
The DocMaster class is something like this :
#Entity
#Table(name="DOC_MASTER")
public class DocMaster {
#Id
#NotNull
#Column(name = "BARCODE")
private String barcode;
#Column(name = "DOC_NO")
private String docNo ;
#Column(name="DOC_TYPE")
private String docType;
#Column(name="STATUS")
private String status;
// other fields and getters setters
}
When I am trying to run following code :
Criteria criteria = session.createCriteria(DocMovement.class,"documentMovement");
criteria.add(Restrictions.eq("documentMovement.recipientDetail.empId", empId));
criteria.add(Restrictions.eq("documentMovement.isCurrent", true));
criteria.add(Restrictions.ne("documentMovement.docMaster.status",FMSConstants.CLOSED_STATUS));
criteria.add(Restrictions.ne("documentMovement.docMaster.status",FMSConstants.DISPOSED_STATUS));
List<DocMovement> documentsHeld = (List<DocMovement>) criteria.list();
then I get the following exception :
[org.hibernate.QueryException: could not resolve property:
docMaster.status of: com.fms.persistence.DocMovement] with root cause
org.hibernate.QueryException: could not resolve property:
docMaster.status of: com.fms.persistence.DocMovement
there are other cases where I try to make query using criteria as shown above, the query runs fine, but I am unable to understand what am I doing wrong in this case. I have tried using eager fetch too, earlier I was not using an alias, so I tried using an alias too.
Please help me solve the issue !!!
Try adding alias :
criteria.createAlias("documentMovement.docMaster", "docMaster")
And later call
criteria.add(Restrictions.ne("docMaster.status",FMSConstants.CLOSED_STATUS));
You have to add an alias to docMaster first
I think that it's the comparaison with the enums that are not correct. You are trying to compare an enum with a String. This line seems wrong:
criteria.add(Restrictions.ne("documentMovement.docMaster.status",FMSConstants.CLOSED_STATUS));
Since documentMovement.docMaster.status is defined as a String, maybe try:
criteria.add(Restrictions.ne("documentMovement.docMaster.status",FMSConstants.CLOSED_STATUS.toString()));
criteria.add(Restrictions.ne("documentMovement.docMaster.status",FMSConstants.DISPOSED_STATUS.toString()));