Handle null in JPQL query

32 views Asked by At
@Query("SELECT new com.abc.cba.domain.Attachment(ia.createdBy, ia.fileName, ia.contentType, ia.someClass, ia.otherClass) from Attachment ia where ia.someClass=?1")
Attachment findAllBySomeClass(SomeClass someClass);    

Constructor:

public Attachment(User createdBy, String fileName, String contentType, SomeClass someClass, OtherClass otherClass) {
    this.createdBy = createdBy;
    this.fileName = fileName;
    this.contentType = contentType;
    this.someClass = someClass;
    this.otherClass = otherClass;
}    

If the values for ia.createdBy, ia.fileName, ia.contentType, ia.someClass, ia.otherClass are null, then the Attachment object gets created where all the property values are null.

When I call the method like below

Attachment attachment = repository.findAllBySomeClass("attachment");
Long userid = attachment != null ? attachment.getCreatedBy : 0L;

The above statement throws a null pointer exception. When I debugged the code, I can see that the attachment object exists like Attachment@564435 with the hashcode and all the property values such as fileName, createdBy inside the attachment object are null. But why does attachment.getCreatedBy throw a null pointer exception in this case as it should have returned 0 when the attachment is null. Can you please help with this as I am confused why this code is throwing an exception?

0

There are 0 answers