I have 2 entities: DocumentEntity (docNumber (primary key), dateOfFill, ...) and FileEntity (id, title, size, ...). I have an HQL query with inner join of 2, which should run on Oracle DB:
String queryStr = "SELECT docNumber " +
+ "FROM DocumentEntity d " +
+ "INNER JOIN FileEntity f " +
+ "ON d.docNumber = f.title " +
+ "WHERE d.date > to_date('01.01.2011','dd.mm.yyyy')"
Query query = em.createQuery(query_string);
return query.getResultList();
When I run the code snippet I'm getting an exception org.hibernate.hql.ast.QuerySyntaxException: Path expected for join!
I looked through
Hibernate 4.3.6 QuerySyntaxException: Path expected for join
HQL ERROR: Path expected for join
Path Expected for Join! Nhibernate Error
HQL Hibernate INNER JOIN
but none resolved my problem. The suggested paths cannot be used in this example (at least it gives wrong path error). The answer of the last link says that:
Joins can only be used when there is an association between entities.
The issue is that I cannot associate these 2 entities.
The question is:
How can I join these 2 entities?
UPDATE:
My entities are:
#Entity
#Table(name = "DOCUMENT")
public class DocumentEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "DOC_NUMBER", nullable = false)
private String docNumber;
#Basic(optional = false)
#Column(name = "DATE_OF_FILL")
#Temporal(TemporalType.DATE)
private Date dateOfFill;
...
}
and
#Entity
#Table(name = "FS_FILE")
public class FileEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name = "FS_FILE_SEQ", allocationSize = 1, sequenceName = "FS_FILE_SEQ")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "FS_FILE_SEQ")
#Column(name = "ID", nullable = false)
protected Long id;
#Column(name = "TITLE", nullable = false)
protected String title;
#Column(name = "MIMETYPE", nullable = false)
protected String mimetype;
#Column(name = "FILESIZE", nullable = false)
protected Long filesize;
#Column(name = "FILEPATH", nullable = false)
protected String filepath;
...
}
In this case, you don't need to do a join since you limit the result with the condition d.docNumber = f.title.
Just add the condition in the where clause and use a SQL query instead of a JPQL query since it seems more matching to your need.
String sqlString= "SELECT d.docNumber " +
+ "FROM DOCUMENT d, FS_FILE f " +
+ "WHERE d.docNumber = f.title " +
+ "AND d.date > to_date('01.01.2011','dd.mm.yyyy')"
Query query = em.createNativeQuery(sqlString);
return query.getResultList();
Related
Entity name is similar to name of the table.
#Table
#Entity(name = "CKYCUploadTransactions")
#Access(AccessType.FIELD)
#NamedQueries({
#NamedQuery(name = "CKYCUploadTransactions.byUserId", query = "select k from CKYCUploadTransactions k where" +
"k.userId = :user_id"),
#NamedQuery(name = "CKYCUploadTransactions.byUserIdAndTxnTypeAndStatus", query = "select k from CKYCUploadTransactions k where" +
"k.userId = :user_id AND k.txnType = :txn_type AND k.status = :status"),
#NamedQuery(name = "CKYCUploadTransactions.byUserIdAndContext", query = "select k from CKYCUploadTransactions k where" +
"k.userId = :user_id and k.context = :context")
})
#Data
public class CKYCUploadTransactions {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "user_id")
private String userId;
#Column(name = "context")
private String context;
#Column(name = "txn_type")
private String txnType;
#Enumerated(EnumType.STRING)
#Column(name = "status", length = 20)
private Status status;
public enum Status{
initiated,
success,
failed
}
}
I am not understanding why it is throwing this error, I have created another entity like this but not facing the issues there.
Exception: Errors in named queries: CKYCUploadTransactions.byUserIdAndTxnTypeAndStatus, CKYCUploadTransactions.byUserIdAndContext, CKYCUploadTransactions.byUserId
You can follow this JPA Named Queries
CKYCUploadTransactions.byUserId
should be
CKYCUploadTransactions.findByUserId
I'm using Spring boot 2.3.12.RELEASE and Hibernate 5.4.32.Final. I'm using JOINED inheritance strategy for several classes with parent entity mapped like this:
#Entity
#Table(name = "dos_t_requests")
#Inheritance(strategy = InheritanceType.JOINED)
public abstract class Request {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sq_requests")
#SequenceGenerator(name = "sq_requests", sequenceName = "dos_sq_requests", allocationSize = 1)
private long id;
#Column(name = "req_num")
private String number;
#Column(name = "created_at")
private LocalDateTime createdAt;
#Column(name = "edited_at")
private LocalDateTime editedAt;
#Column(name = "executed_at")
private LocalDateTime executedAt;
#Column(name = "issued_at")
private LocalDateTime issuedAt;
#Lob
#Column(name = "message")
private String message;
...
}
And here is one of child entities:
#Entity
#Table(name = "dos_t_stud_reqs")
#PrimaryKeyJoinColumn(name = "id")
public class StudentRequest extends Request {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "stud_id")
private Student student;
...
}
I need to count the total number of rows of child entities to paginate the results. So I have a method that does all the work:
public Page<RequestPartInfo> getAll(DbUser dbUser, int page, int pageSize) {
...
String cntQuery;
String entQuery;
if (dbUser.getDbType() == DbUserType.STUDENT) {
cntQuery = String.join("\n",
"select count(r.id)",
"from StudentRequest r",
"where r.student.id = :userId");
entQuery = String.join("\n",
"from StudentRequest r",
"join fetch r.document d",
"join fetch d.recipient rc",
"join fetch r.curator c",
"join fetch r.executor e",
"join fetch r.issueType it",
"join fetch r.status st",
"where r.student.id = :userId",
"order by r.createdAt desc");
}
...
long count = em.createQuery(cntQuery, Long.class).setParameter("userId", dbUser.getId()).getSingleResult();
List<RequestPartInfo> requests = em.createQuery(entQuery, Request.class).setParameter("userId", dbUser.getId())
.setFirstResult(page * pageSize).setMaxResults(pageSize).getResultList()
.stream().map(this::mapPartInfo).collect(Collectors.toList());
return PagingUtil.createPage(requests, page, pageSize, count);
}
When I call this method, Hibernate generates an incorrect database query:
select count(studentreq0_.id) as col_0_0_ from oksana.dos_t_stud_reqs studentreq0_ where studentreq0_.id=studentreq0_1_.id and studentreq0_.stud_id=?
The problem with this request is that the WHERE section uses an alias that is not present in the FROM section. So I get following error: java.sql.SQLSyntaxErrorException: ORA-00904: "STUDENTREQ0_1_"."ID": invalid identifier.
I tried to search for a solution to the problem on the internet and found a similar problem here. But it says that this bug has been fixed in Hibernate 5.4.19.
I'm trying to apply the where condition on the related entity, but the result set contains all the related entity data. It appears like the filter is ignored.
I have the following entities:
Entity Audit:
#Entity
#Table(name = "entity_audit")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#org.springframework.data.elasticsearch.annotations.Document(indexName = "entityaudit")
public class EntityAudit implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#org.springframework.data.elasticsearch.annotations.Field(type = FieldType.Keyword)
private Long id;
#NotNull
#Column(name = "entity_id", nullable = false)
private Long entityId;
#NotNull
#Column(name = "entity_class_name", nullable = false)
private String entityClassName;
#NotNull
#Column(name = "entity_name", nullable = false)
private String entityName;
#NotNull
#Enumerated(EnumType.STRING)
#Column(name = "action_type", nullable = false)
private EntityAuditType actionType;
#NotNull
#Column(name = "timestamp", nullable = false)
private Instant timestamp;
#NotNull
#Column(name = "user", nullable = false)
private String user;
#NotNull
#Column(name = "transaction_uuid", nullable = false)
private String transactionUuid;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
#JoinColumn(name = "entity_audit_id")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<EntityAuditUpdateData> entityAuditUpdateData = new HashSet<>();
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
#JoinColumn(name = "entity_audit_id")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<EntityAuditStatus> entityAuditStatuses = new HashSet<>();
Getters and setters...
Entity Audit Status
#Entity
#Table(name = "entity_audit_status")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#org.springframework.data.elasticsearch.annotations.Document(indexName = "entityauditstatus")
public class EntityAuditStatus implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#org.springframework.data.elasticsearch.annotations.Field(type = FieldType.Keyword)
private Long id;
#NotNull
#Column(name = "user_login", nullable = false)
private String userLogin;
#NotNull
#Column(name = "jhi_read", nullable = false)
private Boolean read;
#ManyToOne
private EntityAudit entityAudit;
Getters and setters...
I'm trying to achieve this query:
#Query("select distinct entityAudit from EntityAudit entityAudit " +
"join entityAudit.entityAuditStatuses entityAuditStatus " +
"where entityAuditStatus.userLogin =:userLogin " +
"order by entityAudit.timestamp desc")
Page<EntityAudit> retrieveAllByUserLogin(#Param(value = "userLogin") String userLogin, Pageable pageable);
But when I retrieve the data the EntityAuditStatuses are not filtered. I don't understand where the problem is.
Note: I removed the date property from the minimum reproducible example.
Use left join fetch instead of left join to make sure the dependent entityAuditStatuses are fetched as part of the join query itself, and not as multiple queries after finding the entityAudit. And since the result needs to be paginated, an additional countQuery will need to be specified (without the fetch). Working Query -
#Query(value = "select entityAudit from EntityAudit entityAudit " +
"left join fetch entityAudit.entityAuditStatuses entityAuditStatus " +
"where entityAuditStatus.userLogin = :userLogin ",
countQuery = "select entityAudit from EntityAudit entityAudit " +
"left join entityAudit.entityAuditStatuses entityAuditStatus " +
"where entityAuditStatus.userLogin = :userLogin ")
Without left join fetch, three queries are being generated - one which fetches the entityAuditId 1 (based on the userLogin 1) and then two more to fetch the entityAuditStatuses (from the entity_audit_status table only without the join) given the entityAuditId 1.
That is why, when you ask for userLogin = '1' - you retrieve the EntityAudit 1 which brings with it - entityAuditStatus 1 - entityAuditStatus 3 (which has userLogin = '2')
After adding left join fetch, there is only one query using join as per the defined entity relationships. So the results are correctly fetched.
i m trying to run a HQL query which is giving me error saying:
org.hibernate.QueryException: could not resolve property:
UserType of: EntityPack.UserTypeMenu
[from EntityPack.UserTypeMenu as utm ,EntityPack.UserType as ut
where utm.UserType.userTypeId=ut.userTypeId and ut.userTypeDesc like ' %ad%' ]
this is the function where i write query :
public ObservableList PostTableusertypemenu(String search, int q) {
ObservableList data;
data = FXCollections.observableArrayList();
List ll=null;
ll = pop.UrviewTable("from UserTypeMenu as utm ,UserType as ut "+
"where utm.UserType.userTypeId=ut.userTypeId"+
" and ut.userTypeDesc like ' %"+ search +"%' ");
Iterator ite = ll.iterator();
while (ite.hasNext()) {
UserTypeMenu obj = (UserTypeMenu) ite.next();
data.add(obj);
}
return data;
}
my UserType entity class :
#Entity
#Table(name = "user_type")
public class UserType {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Basic(optional = false)
#Column(name = "User_Type_Id")
private Integer userTypeId;
#Basic(optional = false)
#Column(name = "User_Type")
private String userType;
#Basic(optional = false)
#Column(name = "User_Type_Desc")
private String userTypeDesc;
#Basic(optional = false)
#Column(name = "Status")
private String status;
#Basic(optional = false)
#Column(name = "Markers")
private String markers;
}
UserTypeMenu Entity class :
#Entity
#Table(name = "user_type_menu")
#NamedQueries({
#NamedQuery(name = "UserTypeMenu.findAll", query = "SELECT u FROM UserTypeMenu u")})
public class UserTypeMenu implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Basic(optional = false)
#Column(name = "User_Type_Menu_Id")
private Integer userTypeMenuId;
#Basic(optional = false)
#Column(name = "Status")
private String status;
#Basic(optional = false)
#Column(name = "Markers")
private String markers;
#ManyToOne(optional = false)
private UserType userType;
#ManyToOne(optional = false)
private UserMenuMaster userMenuMaster;
#ManyToOne(optional = false)
private UserMenuBar userMenuBar;
}
what i want is to get data from UsertypeMenu based on Usertype description.
please help me..
thank you. :)
You don't write joins in HQL like in SQL, you use . notation to navigate through object graph. Try this
"from UserTypeMenu as utm where utm.userType.userTypeDesc like ' %"+ search +"%' "
Actually, you can use joins but directly on associations. Here is the same query but using join syntax
"from UserTypeMenu as utm join utm.userType ut where ut.userTypeDesc like ' %"+ search +"%' "
The benefit of using joins here is that you can specify, for example, left join if the relation is not mandatory and you don't want to lose any results because of inner join which is implicitly used when you use ..
I have the main entity class with the below fields where there is a field finid which references patient entity class. :-
public class Patientrel implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "patientrelid")
private Long patientrelid;
#Column(name = "entrydate")
#Temporal(TemporalType.TIMESTAMP)
private Date entrydate;
#JoinColumn(name = "finid", referencedColumnName = "fin_id")
#ManyToOne
private Patient finid;
Entity class of Patient :-
public class Patient implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "fin_id")
private Integer finId;
#Size(max = 100)
#Column(name = "patient_name")
private String patientName;
#OneToMany(mappedBy = "finid")
private Collection<Patientrel> patientrelCollection;
Now i need to search patientrel matching a given finid. Can anyone please share the approach for that?
Now i need to search patientrel matching a given finid.
First option is to get the Patient by finId, and then retrieve the Patientrel collection thru .getPatientrelCollection() getter method:
EntityManager em = ...
Integer findId = 1;
Patient patient = em.find(Patient.class, findId );
Collection<Patientrel> patientrelCollection = patient.getPatientrelCollection();
Second option is to to use a JQL query which joins Patient and Patientrel entities to "search" for patientrels matching a given finid:
EntityManager em = ...
Integer findId = 1;
Query q = entityManager.createQuery(
"SELECT prel FROM " + Patient.class.getName() + "p " +
"join p.patientrelCollection prel " +
"WHERE p.finId = :id");
q.setParameter("id", findId);
List<Patientrel> patientrel = (List<Patientrel>)q.getResultList();