Hibernate - org.hibernate.QueryException: could not resolve property: - java

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

Related

generate hibernate query from java pojo class

I want to make hibernate query from pojo class, but pojo class uses mappedBy. I don't know how can I make proper query.
Already I have tried many ideas, like ts.clientAccount.clientAccountMapping.id but it gives error. clientAccountMapping is mapped in clientAccount pojo
first class
public class Transaction{
#ManyToOne
#JoinColumn
private ClientAccount clientAccount;
}
second class
public class ClientAccount{
#JsonIgnore
#OneToMany(mappedBy = "clientAccount", cascade = CascadeType.ALL)
private Set<ClientAccountMapping> clientAccountMapping;
}
third class
public class ClientAccountMapping{
#Id
#GeneratedValue(generator="system-uuid")
#GenericGenerator(name="system-uuid", strategy = "uuid")
private String id;
}
Always my compiler gives the following exception:
org.hibernate.QueryException: illegal attempt to dereference collection [transactio0_.idtransactio0_.clientAccount_accountIdclientAccount.clientAccountMapping]
you have to use join here. like : From ClientAccount c join c.clientAccountMapping
Reference : https://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html

JPA: dealing with Views

I'm trying to implement a Repository to work with Views. The fact is that I'm trying to use the SimpleJpaRepository implementation, but I'm getting a lot of errors on execution time because my DTO is not an #Entity. It is only a #Table, and it seems that this kind of elements are not mapped into the Metamodel of JPA.
This is my DTO:
#Table(name = "v_language")
public class VLanguage {
#Column(name = "isocode")
private String isocode;
#Column(name = "name")
private String name;
#Column(name = "isdefault")
private String isdefault;
// getters and setters
...
}
I tried to define a customized base repository with minimal functionality (only a findAll() method) with the same implementation of SimpleJpaRepository, but when building the Query it fails when doing:
Root<U> root = query.from(domainClass);
With this exception:
Caused by: java.lang.IllegalArgumentException: Not an entity: class es.prodevelop.pui.common.jpa.model.views.dto.VLanguage
at org.hibernate.jpa.internal.metamodel.MetamodelImpl.entity(MetamodelImpl.java:194)
at org.hibernate.jpa.criteria.QueryStructure.from(QueryStructure.java:124)
at org.hibernate.jpa.criteria.CriteriaQueryImpl.from(CriteriaQueryImpl.java:156)
at es.prodevelop.pui.common.jpa.configuration.AbstractRepository.applySpecificationToCriteria(AbstractRepository.java:213)
at es.prodevelop.pui.common.jpa.configuration.AbstractRepository.getQuery(AbstractRepository.java:174)
at es.prodevelop.pui.common.jpa.configuration.AbstractRepository.findAll(AbstractRepository.java:151)
...
Does anybody know how to solve it?
you are missing the #Entity annotation.
please annotate your class and try again.

HQL where clause with String collection type

I want to do a search ob the basis of some variables provided by user.
What I am doing to achieve data from tables collection:
Here is my entity:
#Entity
#Table
public class FrontRequest implements Serializable {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private Long tutorfront_id;
#Column
private String tutorialType;
#Column
private String tutorialLevel;
#ElementCollection(fetch=FetchType.EAGER)
#Fetch(value = FetchMode.SELECT)
private Collection<String> tutorialSubjects= new HashSet<String>();
#Column
private String tutorialCity;
#Column
private String noOfStudent;
#Column
private String classWeek;
#Column
private String tutionFee;
#Column
private String tutionFeerate;
#Column
private String tutorSex;
#Column
private String tutorEducation;
#Column
private Date postingDate;
#Column
private String studentSchool;
}
Now I want to fetch FrontRequest objects as list, here I have a subject as input.
Now I want to get FrontRequest here subject in FrontRequest.TutorialSubjects.
For this I was trying to do like below:
Query query=session.createQuery("from FrontRequest frontreq where :tutorialsubject IN frontreq.tutorialSubjects");
query.setParameter("tutorialsubject", tutorialSubject);
List<FrontRequest> frontRequest=query.list();
But its giving exception with invalid syntax.
I don't know where I am wrong. May be I am doing it wrong way.
Yes the issue is same like
Issue when trying to use the IN operator in a JPQL query
but, its slightly different from that, i.e. I am using string type collection here in my entity. And when I am trying to use member of here, its not working with that and throwing an exception
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected end of subtree [from com.tutor.entity.FrontRequest frontreq where frontreq.tutorialCity like '%' and :tutorialsubject MEMBER OF frontreq.tutorialSubjects]
Please help.
Thanks in advance.
Finally I have resolved the problem with "In elements" in where clause.
Query is :
from FrontRequest frontreq where :tutorialsubject IN elements (frontreq.tutorialSubjects)
query.setParameter("tutorialsubject", tutorialSubject);
List<FrontRequest> frontRequest=query.list();
Thanks to All, should give +1 to it.

hibernate - could not execute statement; SQL [n/a] - saving nested object

I'm trying to save a nested object using hibernate and I receive could not execute statement; SQL [n/a] Exception
CODE
#Entity
#Table(name = "listing")
#Inheritance(strategy = InheritanceType.JOINED)
public class Listing implements Serializable {
#Id
#Column(name = "listing_id")
private String listingId;
#Column(name = "property_type")
private PropertyType propertyType;
#Column(name = "category")
private Category category;
#Column(name = "price_currency")
private String priceCurrency;
#Column(name = "price_value")
private Double priceValue;
#Column(name = "map_point")
private MapPoint mapPoint;
#Column(name = "commission_fee_info")
private CommissionFeeInfo commissionFeeInfo;
}
public class MapPoint implements Serializable {
private final float latitude;
private final float longitude;
}
public class CommissionFeeInfo implements Serializable {
private String agentFeeInfo;
private CommissionFeeType commissionFeeType;
private Double value;
private Double commissionFee;
}
public enum CommissionFeeType implements Serializable { }
Using RazorSQL I saw that hibernate defines MapPoint and CommissionFee as VARBINARY
What I can't understand, is the fact that hibernate manages to save it when commissionFeeInfo is not present. It has no problem with saving MapPoint
Does anyone have an idea about what I do wrong?
UPDATE
I found out that if all attributes of CommissionFeeInfo excepting agentFeeInfoare null, the object will be saved without problems. If one of the other attributes is != null, the errors occur.
UPDATE 2
I changed the type of all attributes of CommissionFeeInfo into String and the object will be saved without problem, but I can't let the attributes as String.
I solved the problem by adding setting
#Column(name = "commission_fee_info", columnDefinition = "LONGVARBINARY")
as annotation for the field commisionFeeInfo in the class Listing
For me,
#Column(columnDefinition="text")
solves my problem.
That solution could help for a different reason. One other reason could be Column length. Check your column length. I had the same error the reason was my data exceed the size of the column.
setSignInProvider("String length > 15 ")
Before
#Column(name = "sing_in_provider", length = 15)
and then
#Column(name = "sing_in_provider", length = 100)
I was also facing the same issue . and then I solved the problem
spring.jpa.hibernate.ddl-auto=update
For me I'm using current_date for a field in my sql table. but this is a keyword in SQL so I can't use this name. I changed the field name to current_date_and_time it works for me. also I added the column name on my entity class.
#Column(name = "current_date_and_time")

Hibernate upgrade from 3 to 4: Criteria transaction ceases to work

I have recently upgraded Spring 2.5 to 3.2 and Hibernate 3 to 4.2.8 in a general upgrade of a web application. Most things are working now, but there is one Criteria transaction that is not working and has me puzzled. The new version returns no result (but no errors), while the old one retrieved properly the requested value.
The code is the same one in the old and new versions, and I have verified that the argument that reaches it is the same. Here is the Java code:
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ViewingResource.class);
criteria.createCriteria("viewings","currentViewings");
criteria.add(Property.forName("currentViewings.id").eq(viewingId));
ViewingResource result = (ViewingResource)criteria.uniqueResult();
ViewingResource is my entity, which is defined as follows:
#Entity
#DiscriminatorValue("viewing")
public class ViewingResource extends AbstractInformationResource {
private static final long serialVersionUID = -4569093742552159052L;
#OneToOne(targetEntity = Attribute.class, fetch = FetchType.LAZY)
#JoinColumn
private Attribute primaryAttribute;
#OneToMany(targetEntity = Viewing.class, cascade = {CascadeType.PERSIST, CascadeType.MERGE}, orphanRemoval=true)
#Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
#JoinTable(name = "informationresource_viewings")
#OrderBy("sort")
private Set<ResourceViewing> viewings;
public Set<ResourceViewing> getViewings() {
return viewings;
}
public Attribute getPrimaryAttribute() {
return primaryAttribute;
}
}
As for the abstract class it extends:
#Entity
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(
name = "type",
discriminatorType = DiscriminatorType.STRING
)
#Table(name = "informationresource")
abstract public class AbstractInformationResource extends PersistentEntity<String> {
private static final long serialVersionUID = 8709376067232042462L;
#Id #GeneratedValue(generator="system-uuid")
#GenericGenerator(name="system-uuid", strategy = "uuid")
private String id;
#Column(nullable = false)
private String name;
#Column(nullable = false)
private int sort;
public String getId() {
return id;
}
public String getName() {
return name;
}
public int getSort() {
return sort;
}
}
And the original PersistentEntity is just an extension of Serializable with an id and no annotations.
I enabled Hibernate logs and found the problem may be in the way annotations work between in Hibernate 3 and 4, for the Hibernate generated SQL strings differ in this way:
Hibernate 3:
select
... (maps to all columns)
from
informationresource this_
inner join
informationresource_viewings viewings3_
on this_.id=viewings3_.informationresource_id
inner join
Viewing currentvie1_
on viewings3_.viewings_id=currentvie1_.id
where
this_.type in (
'viewing', 'directory'
)
and currentvie1_.id=?
Whereas in Hibernate 4, the generated SQL performs no joins:
select
... (maps to all columns, except type, attributeType and fieldName)
from
informationresource this_,
informationresource_viewings viewings3_,
Viewing currentvie1_
where
this_.id=viewings3_.informationresource_id
and viewings3_.viewings_id=currentvie1_.id
and this_.type='viewing'
and currentvie1_.id=?
Any hints that may help me advance with this issue? My current guess is that maybe I skipped some annotation definition that has been changed or modified since Hibernate 3, but so far I haven't been able to find anything illegal in the way I declare them - and my attempts to modify the #Join have been unsuccessful so far.
EDIT. After toying with this for some time, I have found that the issue may be related to the #DiscriminatorColumn of the abstract class. I have found that the problem lies that my type for this kind of request is never 'viewing', but 'directory'. In the old generated SQL I had both types generated:
this_.type in (
'viewing', 'directory'
)
But in the new sql this is constrained to 'viewing':
and this_.type='viewing'
I have changed in the new SQL this line, and it returns the right values that I need. The column type has only those two values, 'viewing' and 'directory'. So my question now is how to make Criteria to keep asking for the types there instead of forcing 'viewing' type.
Finally I found the solution, thanks to the hint I appointed in the EDIT block.
The solution came from establishing a formula in the base class:
#DiscriminatorFormula("case when type in ('viewing','directory') then 1 else 2 end")
And then changing in viewing resource the discriminator value annotation:
#DiscriminatorValue("1")
I really don't know why in Hibernate 3 I got all the values in the discrimination, and in Hibernate 4 the value was only this one, since the code had not changed at all. So if anyone in the future sees some similar behavior, maybe this trick can help you.

Categories