Hibernate - Query Result contains null and throws expection - spring

I have two tables, TBL_MARKET_WATCH_NAME (Master) and TBL_MARKET_WATCH (Details) connected through an MW_ID column in MySQL. I'm using hibernate and doing a LEFT JOIN on these two tables to fetch data. Most of the time the Details table may not have data for the connecting ID column from left table which results in null values in resultset.
Master table is defined as
#Entity(name = "TBL_MARKET_WATCH_NAME")
#Id
#GeneratedValue
#Column(name = "ID")
private Long id;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "MW_ID")
private List<MarketWatchScripDetailsDTO> mwDetailsDTO;
#Column(name = "MW_ID")
private Integer mwId;
#Column(name = "USER_ID")
private String userId;
#Column(name = "MW_NAME")
private String mwName;
The Details table is defined as below
#Entity(name = "TBL_MARKET_WATCH")
#Id
#GeneratedValue
#Column(name = "ID")
private Long id;
#Column(name = "USER_ID")
private String userId;
#Column(name = "MW_ID")
private Integer mwId;
#Column(name = "SCRIP_NAME")
private String scripName;
In Master table, I have data like below
In Details table, I have data as below
I have a left join query running on Hibernate as below
#Transactional
#Query(value = "SELECT A.mwName as mwName, B.userId as userId, B.mwId as mwId, B.scripName as scripName FROM TBL_MARKET_WATCH_NAME as A LEFT JOIN A.mwDetailsDTO B on A.mwId = B.mwId and A.userId = B.userId where A.userId = :pUserId")
When running the query and converting it into an object my resultset is as below
List<Object> getUserScripDetailsNew(#Param("pUserId") String pUserId);
[
"LIST0",
"650156",
1,
"NATURALGAS 26OCT22 FUT",
],
.... <***some more data***>
[
"LIST2",
null,
null,
null
]
Instead of List if I use model interface like the one defined below, I'm getting null pointer exception because it is not able to convert null values to integer.
List<MwTblResponseModel> getUserScripDetailsNew(#Param("pUserId") String pUserId);
public interface MwTblResponseModel {
public String getMwName();
public String getUserId();
public Integer getMwId();
public String getScripName();
}
The error is as below.
java.lang.NullPointerException
at in.codifi.marketwatch.model.MwTblResponseModel_e3fe8bfde9ba7f8b10664ce55c6c5ef842396ab4.convert_getUserScripDetailsNew(Unknown Source)
at in.codifi.marketwatch.dao.repos.MarketWatchNameRepository_486524f74fd05ac96e0dcf8fffaa2af5a4b95b43Impl$$function$$1.apply(Unknown Source)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
at org.hibernate.query.spi.StreamDecorator.collect(StreamDecorator.java:209)
at in.codifi.marketwatch.dao.repos.MarketWatchNameRepository_486524f74fd05ac96e0dcf8fffaa2af5a4b95b43Impl.getUserScripDetailsNew(Unknown Source)
at in.codifi.marketwatch.dao.repos.MarketWatchNameRepository_486524f74fd05ac96e0dcf8fffaa2af5a4b95b43Impl_Subclass.getUserScripDetailsNew$$superforward1(Unknown Source)
at in.codifi.marketwatch.dao.repos.MarketWatchNameRepository_486524f74fd05ac96e0dcf8fffaa2af5a4b95b43Impl_Subclass$$function$$8.apply(Unknown Source)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:53)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.proceed(InvocationInterceptor.java:62)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.monitor(InvocationInterceptor.java:49)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor_Bean.intercept(Unknown Source)
at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:40)
at io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:32)
at in.codifi.marketwatch.dao.repos.MarketWatchNameRepository_486524f74fd05ac96e0dcf8fffaa2af5a4b95b43Impl_Subclass.getUserScripDetailsNew(Unknown Source)
How to make sure when null values are coming from Query to assign 0 in final response?

Related

QueryDSL Null Pointer exception left join unrelated tables

I have got two tables which are unrelated . Below are the entity classes .
UsersStaging
#Entity
#Table(name = "users_staging")
#Data
public class Usersstaging implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
#GenericGenerator(name = "native", strategy = "native")
#Column(name = "id", updatable = false, nullable = false)
private Integer id;
#Column(name = "employee_id", length = 10)
private String employeeId;
#Column(name="user_name")
private String userName;
#Column(name = "email")
private String email;
Roles table
#Entity
#Table(name = "user_roles")
#Data
#TypeDefs({ #TypeDef(name = "json", typeClass = JsonType.class) })
public class UserRoles implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "employeeId", length = 10)
private String employeeId;
#Column(name = "username")
private String username;
#Type(type = "json")
#Column(name = "roles", columnDefinition = "json")
private List<String> roles;
}
I am trying to write the below query by using left join on username column. Query works fine as long as there are predicates(exp) for UsersStaging table . But if I add a predicate for userRoles table (roleExp) , the query fails .
JPAQuery<UsersStaging> query = new JPAQuery<>(entityManager);
QUsersStaging usersStagingPath = QUsersStaging.usersStaging;
QUserRoles userRolesPath = QUserRoles.userRoles;
BooleanExpression exp = usersStagingPath.legalFirstName
.containsIgnoreCase(criteria.getValue());
BooleanExpression roleExp = userRolesPath.roles.any().eq("SUPERADMIN");
return query
.select(Projections.constructor(UsersStagingDTO.class, usersStagingPath.employeeId,
usersStagingPath.userName, usersStagingPath.email, usersStagingPath.isActive,
usersStagingPath.legalFirstName, usersStagingPath.legalLastName, usersStagingPath.legalFullName,
userRolesPath.roles))
.from(usersStagingPath).leftJoin(userRolesPath).on(usersStagingPath.userName.eq(userRolesPath.username))
.where(exp.and(roleExp)).limit(10).fetch();
}
Getting the below exception
java.lang.NullPointerException: null
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromJoinElement(HqlSqlWalker.java:432) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.joinElement(HqlSqlBaseWalker.java:4007) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3793) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3671) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:746) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:602) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.collectionFunctionOrSubselect(HqlSqlBaseWalker.java:5020) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:4713) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2180) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2108) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:841) ~[hibernate-core-5.6.10.Final.jar:5.6.10.Final]
I was able to resolve it . The issue was that roles field is a json type column and JSON_CONTAINS function is not supported by Hibernate yet .
To fix it , I implemented the MetadataBuilderContributor interface .
public class SQLFunctionContributor implements MetadataBuilderContributor {
#Override
public void contribute(MetadataBuilder metadataBuilder) {
metadataBuilder.applySqlFunction("json_contains_key",
new SQLFunctionTemplate(BooleanType.INSTANCE, "JSON_CONTAINS(?1, JSON_QUOTE(?2))"));
}
}
Add the below line in application.properties so that Hibernate can register the contrib SQL function .
spring.jpa.properties.hibernate.metadata_builder_contributor=com.xxx.xxx.utils.SQLFunctionContributor
I modified my query in below way and no issues.
BooleanExpression roleExp = Expressions.booleanTemplate("json_contains_key({0}, {1})", userRolesPath.roles,
Expressions.constant(criteria.getValue())).isTrue();

ERROR: syntax error at or near "." - JPA Pageable

repository:
#Repository
public interface PostRepository extends PagingAndSortingRepository<Post, Long> {
#Query(value = "SELECT p.postComments FROM Post p WHERE p.webId = ?1")
Page<PostComment> findCommentsByWebId(String webid, Pageable pageable);
}
Post entity:
public class Post {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "web_id")
private String webId;
#Column(nullable = false, name = "title")
private String title;
#Column(nullable = false, name = "description")
private String description;
#Column(nullable = false, name = "mature")
private boolean mature;
#OneToOne(mappedBy = "post")
private Cover cover;
#ManyToOne
#JoinColumn(name = "user_id")
private User user;
#OneToMany(mappedBy = "post")
private List<PostView> postViews;
#ManyToMany
#JoinTable(name = "post_tag",
joinColumns = #JoinColumn(name = "post_id"),
inverseJoinColumns = #JoinColumn(name = "tag_id"))
private List<Tag> tags;
#OneToMany(mappedBy = "post")
private List<PostDownvote> postDownvotes;
#OneToMany(mappedBy = "post")
private List<PostUpvote> postUpvotes;
#OneToMany(mappedBy = "post")
private List<PostComment> postComments;
#Column(name = "created_at")
private Timestamp createdAt;
#Column(name = "updated_at")
private Timestamp updatedAt;
}
The problem: When returning plain List<PostComment> from the query method everything works fine. But if I change it to Page<PostComment> (I need total elements count), I get the following error:
2022-08-03 22:29:41.399 ERROR 9192 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: syntax error at or near "."
Position: 14
Hibernate: select tags0_.post_id as post_id1_6_0_, tags0_.tag_id as tag_id2_6_0_, tag1_.id as id1_10_1_, tag1_.name as name2_10_1_ from post_tag tags0_ inner join tag tag1_ on tags0_.tag_id=tag1_.id where tags0_.post_id=?
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
It is very difficult to debug this. Does anyone have any clue on what is wrong?
I need BOTH paging and total amount of elements.
Basically you are not able to fetch the part of the inner collection. But you could reach it from the another side of the bi-directional relationship
#Repository
public interface PostCommentRepository extends PagingAndSortingRepository<PostComment, Long> {
#Query(value = "SELECT pc FROM PostComment pc WHERE pc.post.webId = ?1")
Page<PostComment> findCommentsByWebId(String webid, Pageable pageable);
// or better using Spring Data naming conventions just
Page<PostComment> findAllByPostWebId(String webid, Pageable pageable);
}
If you only need a total count you should avoid querying list of entities which could be very memory intensive.
So in your PostCommentRepository try the following:
long countAllByPost_WebId(String webId);

TransactionSystemException when #Scheduled is used

When I want to use #Scheduled, it throws org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
When I tried to use noRollbackFor=TransactionSystemException - it does not help either...
I even tried to use propagation=NEVER and then the code does not work,because it needs to be transactional. Iam getting those documents ok, but I cannot do blockDocument(document).
How to make it work?
Thank you in advance
#Component
public class ScheduleService {
#Autowired
private DocumentService documentService;
#Scheduled(cron = "0 33 13 * * ?")
public void blockPassedDocuments() {
List<Document> passedDocuments = documentService.getAllPassedDocuments();
if (passedDocuments != null) {
System.out.println("blocked docs "+ passedDocuments.size());
passedDocuments.forEach(document -> documentService.blockDocument(document));
}
}
}
#Service
#Transactional
public class DocumentService {
#Autowired
private DocumentRepository documentRepository;
#Autowired
private UserService userService;
#Autowired
private EmailService emailService;
#Transactional(noRollbackFor = TransactionSystemException.class)
public void blockDocument(Document document){
documentRepository.blockDocument(document);
}
// repository
#Override
public void blockDocument(Document document) {
DocumentState documentState = getDocumentState(3);
document.setDocumentState(documentState);
entityManager.merge(document);
}
#Entity
#Table(name = "document_state")
public class DocumentState {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#NotBlank(message = "State is mandatory")
#Size(min=1, max=60)
#Column(length = 60)
private String state;
#JsonIgnore
#OneToMany(mappedBy = "documentState", cascade= CascadeType.ALL)
private List<Document> documents;
public DocumentState(){
}
#Entity
public class Document {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(unique = true, length = 60, nullable = false)
#NotBlank(message = "Name is mandatory")
private String name;
#NotBlank(message = "Title is mandatory")
#Size(min = 3, max = 15)
#Column(length = 15, nullable = false)
private String title;
#NotBlank(message = "Description is mandatory")
#Size(min = 3, max = 255)
#Column(length = 255, nullable = false)
private String description;
#ManyToOne
#JoinColumn(name = "document_state_id", nullable = false)
private DocumentState documentState;
#JsonIgnore
#Column(name = "resource_path", length = 255, nullable = false)
private String resourcePath;
#Column(name = "upload_datetime", columnDefinition = "DATETIME", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#NotNull(message = "UploadDateTime is mandatory")
private Date uploadDatetime;
#Column(name = "approval_end_time", columnDefinition = "DATETIME", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#NotNull(message = "Approval end time is mandatory")
private Date approvalEndTime;
#Column(name = "active_start_time", columnDefinition = "DATETIME", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#NotNull(message = "Active start time is mandatory")
private Date activeStartTime;
#Column(name = "active_end_time", columnDefinition = "DATETIME", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#NotNull(message = "Active end time is mandatory")
private Date activeEndTime;
#OneToMany(mappedBy = "document", cascade= CascadeType.ALL, orphanRemoval = true)
private Set<UsersDocuments> documentsForUsers = new HashSet<>();
#ManyToOne
#JoinColumn(name="user_id")
private User user;
public DocumentState getDocumentState() {
return documentState;
}
EDIT STACK:
org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:541) ~[spring-orm-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:746) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:714) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:534) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:305) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at com.patrikmaryska.bc_prace.bc_prace.service.ScheduleService$$EnhancerBySpringCGLIB$$68ed607b.blockPassedDocuments(<generated>) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) ~[spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:93) ~[spring-context-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) ~[na:na]
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at java.base/java.lang.Thread.run(Thread.java:835) ~[na:na]
Add the #Transactional annotation on blockPassedDocuments method.
Add the #Transactional annotation on ScheduleService class.

JPQL Insert by selecting query not working

I have two below entity. One is MatchTable another is MatchLog.
#Entity
public class MatchTable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", updatable = false, nullable = false)
private Long id;
#ManyToOne
private Integer primaryID;
#ManyToOne
private Integer suspectedID;
#Column(nullable=false)
private Integer status;
//getter and setter
}
#Entity
public class MatchLog {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", updatable = false, nullable = false)
private Long id;
#OneToOne
private MatchTable referenceID;
#Column(nullable=false)
private Long primaryID;
#Column(nullable=false)
private Long suspectedID;
#Column(nullable=false)
private Integer status;
//getter and setter
}
If status of MatchTable change,these row will be inserted into MatchLog. I have tried with the below JPQL query.
#Query("INSERT INTO MatchLog (referenceID.id,primaryID,suspectedID,status) SELECT id,primaryID,suspectedID,status from MatchTable where (primaryID = :ID or suspectedID = :ID)")
int updateMatchLogTable(#Param("ID") long ID);
But this JPQL query is not working. Please suggest me what will be the JPQL query to insert change rows from MatchTable to MatchLog.
Unless I'm mistaken, JPA does not support "insert into select". You can change as native query.

Why getting org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for join! when joining 3 tables

I have three entity basicInfo, gender and department. If I join with basicInfo and gender model then it works fine but when want to join department along with other two entities same time then showing
.QuerySyntaxException: Path expected for join!
My Three entity classes here,
#Entity
#Table(name = "employeebasicinfo")
public class BasicInfoModel {
#Id private String employeeId;
#NotBlank private String firstName;
#NotBlank private String lastName;
#NotNull private Integer companyId;
#Transient private String companyName;
private String phoneNo;
#Column(name = "sex")
private char sexId;
#Transient private String sexName;
#Temporal(TemporalType.TIMESTAMP)
private Date birthDate;
#Temporal(TemporalType.TIMESTAMP)
private Date joiningDate;
#NotNull private Integer department;
#Transient private String departmentName;
#ManyToOne()
#JoinColumn(name = "sex", referencedColumnName = "id", insertable = false, updatable = false)
private GenderModel genderModel;
#ManyToOne
#JoinColumn(
name = "department",
referencedColumnName = "id",
insertable = false,
updatable = false)
private DepartmentModel departmentModel;
// getter setter
}
Gender Model
#Entity
#Table(name = "gender")
public class GenderModel implements Serializable {
#Id
#Column(name = "id")
private char id;
#Column(name = "name")
private String name;
//getter setter
}
And Department model
#Entity
#Table(name = "department")
public class DepartmentModel {
#Id private int id;
private String name;
//getter setter
}
My Dto class
public class BasicInfoDto {
private String employeeId;
private String firstName;
private String lastName;
private Integer companyId;
private String companyName;
private String phoneNo;
private char sexId;
private String sexName;
private Date birthDate;
private Date joiningDate;
private Integer department;
private String departmentName;
public BasicInfoDto(char sexId, String sexName, int department, String departmentName) {
this.sexId = sexId;
this.sexName = sexName;
this.department = department;
this.departmentName = departmentName;
//getter setter
}
My Repository class is below:
#Repository
public interface BasicInfoRepository extends JpaRepository<BasicInfoModel, String> {
#Query(
value =
"SELECT new com.employeeAttendance.employeeAttendance.dto.BasicInfoDto ("
+ " a.sexId, b.name, a.department,c.name) FROM "
+ " BasicInfoModel a INNER JOIN GenderModel b on a.sexId = b.id" +
" INNER JOIN DepartmentMode c on a.department = c.id")
List<BasicInfoDto> getBasicInfoList();
}
And finally I am getting this error
Caused by: java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for
join! [SELECT new
com.employeeAttendance.employeeAttendance.dto.BasicInfoDto ( a.sexId,
b.name, a.department,c.name) FROM
com.employeeAttendance.employeeAttendance.model.BasicInfoModel a INNER
JOIN com.employeeAttendance.employeeAttendance.model.GenderModel b on
a.sexId = b.id INNER JOIN DepartmentMode c on a.department = c.id]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:713)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:23)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
~[na:1.8.0_191]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
~[na:1.8.0_191]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:350)
~[spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at com.sun.proxy.$Proxy109.createQuery(Unknown Source) ~[na:na]
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:87)
~[spring-data-jpa-2.1.4.RELEASE.jar:2.1.4.RELEASE]
... 76 common frames omitted
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for join! [SELECT new
com.employeeAttendance.employeeAttendance.dto.BasicInfoDto ( a.sexId,
b.name, a.department,c.name) FROM
com.employeeAttendance.employeeAttendance.model.BasicInfoModel a INNER
JOIN com.employeeAttendance.employeeAttendance.model.GenderModel b on
a.sexId = b.id INNER JOIN DepartmentMode c on a.department = c.id]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:74)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.hql.internal.ast.ErrorTracker.throwQueryException(ErrorTracker.java:93)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:277)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:191)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:143)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:119)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:80)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:595)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:704)
~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
... 84 common frames omitted
However, if I remove 2nd join with department then it work fine.
You are working on the entity properties in jpql not on tables. So you only tell jpql which property to use to join:
"SELECT new com.employeeAttendance.employeeAttendance.dto.BasicInfoDto ("
+ " a.sexId, b.name, a.department,c.name) FROM "
+ " BasicInfoModel a INNER JOIN a.genderModel b "
+ " INNER JOIN a.departmentModel c";

Resources