JPA Named Query Returning Empty Array when it Shouldn't - spring-boot

I am trying to query the last 5 digits of a number field from an Oracle DB within a Springboot/JPA Repository.
In Oracle, the following query works:
Select * FROM DP1_Attachments Where trim(substr(dp1_submit_date_dp1_number, -5, 5)) = [a-five-digit-number]
I have tried implementing the following:
ENTITY:
#IdClass(CompositeKey.class)
public class DP1Attachments {
#Id
private Integer attachmentsFolder;
#Id
private Integer attachmentNumber;
private Integer dp1SubmitDateDp1Number;
private String attachmentName;
private Integer attachmentSize;
private String attachmentType;
#JsonFormat(pattern = "MM/dd/yyyy HH:mm")
private LocalDateTime attachmentDate;
private String attachmentBy;
private Integer attachmentByUsersId;
private String attachmentActive;
private String modifiedBy;
private Integer modifiedByUsersId;
#JsonFormat(pattern = "MM/dd/yyyy HH:mm")
private LocalDateTime modifiedDate;
REPOSITORY
#Query("SELECT a FROM DP1Attachments a WHERE trim(substring(a.dp1SubmitDateDp1Number, -5, 5)) = :dp1Number")
List<DP1Attachments> queryByDp1SubmitDateDp1Number(#Param("dp1Number") String dp1Number);
}
SERVICE
public List<DP1Attachments> getAttachmentsList (String dp1Number){
return attachmentsRepository.queryByDp1SubmitDateDp1Number(dp1Number);
}
CONTROLLER
public ResponseEntity<?> getAttachmentsInFolder (#PathVariable String attachmentFolder){
List<DP1Attachments>files = attachmentsService.getAttachmentsList(attachmentFolder);
return new ResponseEntity<>(files, HttpStatus.OK);
}
The query runs but returns an empty array.
I also tried changing the substring to a LIKE statement:
#Query("SELECT a FROM DP1Attachments a WHERE TO_CHAR(a.dp1SubmitDateDp1Number) like :dp1Number")
List<DP1Attachments> queryByDp1SubmitDateDp1Number(#Param("dp1Number") String dp1Number);
And the service changed to :
public List<DP1Attachments> getAttachmentsList (String dp1Number){
return attachmentsRepository.queryByDp1SubmitDateDp1Number("%" + dp1Number);
}
This also runs w/o errors but returns an empty array.

Related

Sprint error querying embedded documents in mongoDB

I have a
#Data
#Document(collection = "req_language")
public class Language implements ChangeDto {
#Id
private String id = UUID.randomUUID().toString();
private String name;
private String code;
private Boolean active = Boolean.TRUE;
private Boolean deleted = Boolean.FALSE;
private Date changeAt = Date.from(Instant.now());
private String changedBy;
private String correlationId = UUID.randomUUID().toString();
}
And
#Data
#Document(collection = "req_locale")
public class Locale implements ChangeDto {
#Id
private String id = UUID.randomUUID().toString();
private String description;
private Language language;
private String code;
private String fatherCode;
private Boolean active = Boolean.TRUE;
private Boolean deleted = Boolean.FALSE;
private Date changedAt = Date.from(Instant.now());
private String changedBy;
private String correlationId = UUID.randomUUID().toString();
}
With a simple repository
#Repository
#JaversSpringDataAuditable
public interface LocalesRepository extends MongoRepository<Locale, String>, LocalesCustom {
List<Locale> findByCode(String code);
}
If a try to use the findByCode, I receive this error:
No converter found capable of converting from type [java.lang.String] to type [XXX.Language]
When I try to use query in the LocalesCustom, for example (empty)
Query query = new Query();
List<Locale> localeList = mongoTemplate.find(query, Locale.class);
Same error
I have tried #DBRef in Language, and popped others errors (I couldn't query by the language code, query.addCriteria(Criteria.where("language.code")) in LocalesRepository.
There's a right way to do it?

Spring Query annotation

I've got problem with Spring #Query annotation. It returns me nothing from postgresql despite of that there are a lot of records. I suppose that it is because of the fact that in db is eg. section_id instead of section column.
From method bellow I have all data.
#Query("select p.id, p.dataContentType, p.changeDate, p.name, p.section.id, p.line.id, p.type.id, "
+ "p.status.id, p.changeUser.id, p.insertDate, p.deletedDate, p.recNum, p.actual, p.previous.id, p.thumbnail "
+ "from Picture p where p.actual=true")
Page<Object[]> findAllWithoutData(Pageable pageable);
However I need method like bellow which returns me Picture:
#Query("select new Picture(p.id, p.dataContentType, p.changeDate, p.name, p.section, p.line, p.type, "
+ "p.status, p.changeUser, p.insertDate, p.deletedDate, p.recNum, p.actual, p.previous, p.thumbnail) "
+ "from Picture p where p.actual=true")
Page<Picture> findAllWithoutData(Pageable pageable);
Here's my entity:
public class Picture implements Serializable {
private Long id;
private byte[] data;
private String dataContentType;
private ZonedDateTime changeDate;
private String name;
private Section section;
private Line line;
private DictionaryValue type;
private DictionaryValue status;
private User changeUser;
private ZonedDateTime insertDate;
private ZonedDateTime deletedDate;
private Long recNum;
private Boolean actual;
private Picture previous;
private byte[] thumbnail;
public Picture(Long id, String dataContentType, ZonedDateTime changeDate, String name, Section section,
Line line, DictionaryValue type, DictionaryValue status, User changeUser, ZonedDateTime insertDate,
ZonedDateTime deletedDate, Long recNum, Boolean actual, Picture previous, byte[] thumbnail) {
this.id = id;
this.dataContentType = dataContentType;
this.changeDate = changeDate;
this.name = name;
this.section = section;
this.line = line;
this.type = type;
this.status = status;
this.changeUser = changeUser;
this.insertDate = insertDate;
this.deletedDate = deletedDate;
this.recNum = recNum;
this.actual = actual;
this.previous = previous;
this.thumbnail = thumbnail;
}
Try something like :
#Query("select p from Picture p where p.actual=true")
Page<Picture> findAllWithoutData(Pageable pageable);
Also, you will need to keep an empty constructor to your entity.

Using Spring JPA Query to populate a pojo

I am using JPA and Hibernate to carry out a simple query. It is a join pulling from two tables, an application table, and a Transaction table. I can see data coming back but it is not able to populate this POJO I created, and it is failing to make the conversion. This is the query:
public interface TransactionRepository extends JpaRepository<Transaction, String>{
#Query(value="SELECT "
+ " TXN.TAX_ID taxId, "
+ " APP.AP_DT apDt, "
+ " TXN.TXN_ID txnId"
+ " FROM "
+ " APPLICATION APP "
+ " JOIN "
+ " TRANSACTION TXN "
+ " ON "
+ " TXN.TXN_ID = APP.TXN_ID "
+ " WHERE"
+ " APP.CONFIRMATION_ID = ?1", nativeQuery=true)
AnnuityNetPdfToFims getInfoForPdfToFims(String confirmationId);
Here is the Transaction Entity
#Entity
#Table(name="\"TRANSACTION\"")
#NamedQuery(name="Transaction.findAll", query="SELECT t FROM Transaction t")
public class Transaction implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="TXN_ID")
private String txnId;
#Column(name="ACCT_NUM")
private String acctNum;
#Column(name="ACCT_TYPE_CODE")
private String acctTypeCode;
#Column(name="AGENT_ID")
private String agentId;
#Column(name="AUTO_SUITABILITY_IND")
private String autoSuitabilityInd;
#Column(name="CARRIER_ID")
private String carrierId;
#Column(name="CHANNEL_NAME")
private String channelName;
#Column(name="COMPANY_NAME")
private String companyName;
#Column(name="DELIVERY_STATE")
private String deliveryState;
#Column(name="FIMS_DOCUMENT_ID")
private String fimsDocumentId;
#Column(name="INTERNAL_CONVERSION_IND")
private String internalConversionInd;
#Column(name="JOINT_OWNER_STATE")
private String jointOwnerState;
#Column(name="OWNER_FIRST_NAME")
private String ownerFirstName;
#Column(name="OWNER_LAST_NAME")
private String ownerLastName;
#Column(name="OWNER_TYPE_CODE")
private String ownerTypeCode;
#Column(name="PERSON_IND")
private String personInd;
#Column(name="PRODUCT_CODE")
private String productCode;
#Column(name="PRODUCT_CUSIP")
private String productCusip;
#Column(name="RESIDENCE_STATE")
private String residenceState;
#Column(name="REVIEWER_ID")
private String reviewerId;
#Column(name="SOLICITATION_STATE")
private String solicitationState;
#Column(name="STATUS_CODE")
private String statusCode;
#Column(name="STEP_ACTION_CODE")
private String stepActionCode;
#Column(name="STEP_NAME")
private String stepName;
#Column(name="TAX_ID")
private String taxId;
#Column(name="TR_BY_ID")
private String trById;
#Column(name="TR_TS")
private Timestamp trTs;
#Column(name="TXN_QUALIFIED_IND")
private String txnQualifiedInd;
#Column(name="TXN_XML")
private String txnXml;
#Column(name="UNIT_ID")
private String unitId;
#Column(name="VENDOR_APP_ID")
private String vendorAppId;
#Column(name="G_NUM")
private String gNum;
#Column(name="XTRAC_WORKITEM_ID")
private String xtracWorkitemId;
public Transaction() {
}
//getters and setters
Here is the Application Entity
#Entity
#NamedQuery(name="Application.findAll", query="SELECT a FROM Application a")
public class Application implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private ApplicationPK id;
#Temporal(TemporalType.DATE)
#Column(name="AP_DT")
private Date apDt;
#Column(name="DTCC_APPSUB_XML")
private String dtccAppsubXml;
#Column(name="PROCESSING_CODE")
private String processingCode;
#Column(name="TXN_ID")
private String txnId;
public Application() {
}
//getters and seters
And here is the POJO I am trying to populate with the query.
public class AnnuityNetPdfToFims
{
private String confirmationId;
private String taxId;
private Date apDt;
private long fimsReturnNum;
private String txnId;
//getters and setters
So I can see that the data is coming back but it is coming back as an Object []. I suppose I could just use that to populate the POJO but I don't think that's very reliable. I have heard that there is a way to use the #SqlResultSetMapping annotation, but have not been able to use it successfully yet. I have also heard that i may be able to specify the actual name of the object in the query like so: How to map a native query to POJO class using jpa and hibernate.
However I am not able to get this to work either. Any suggestions? Thanks in advance.

Spring data mongoDB: Get the distinct rows with pagination

I have User class like,
#Document(collection = "users")
public class User {
private String id;
private String firstName;
private String lastName;
private String jobTitle;
private String email;
private String phoneNumber;
}
And UserDimension as,
#Document(collection = "userDimensions")
public class UserDimension{
private String id;
private String userId;
private String dimensionId;
private String status;
}
I want the userDimension records from mongoDB based on distinct userId with pagination in spring data mongoDB ?
I am using the query like,
Query query = new Query();
List<UserDimension> userDimensionList = null;
// apply pagination parameters to the search criteria
query.with(pageable);
userDimensionList = mongoTemplate.getCollection("userDimensions").distinct("userId", query.getQueryObject());
But it still giving me the total records.

How to search nested object by using Spring Data Solr?

I have two such Java object:
public class PSubject
{
#Column
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
#org.apache.solr.client.solrj.beans.Field("name")
private String name;
#Column
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
#org.apache.solr.client.solrj.beans.Field("type")
private String type;
#Column
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
#org.apache.solr.client.solrj.beans.Field("uri")
private String uri;
#OneToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL)
#IndexedEmbedded
#org.apache.solr.client.solrj.beans.Field("attributes")
private Set<PAttribute> attributes = new HashSet<PAttribute>();
.....
}
#Entity
#Indexed
#Table(name="PAttribute")
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class PAttribute extends PEntity
{
private static final long serialVersionUID = 1L;
#Column
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES)
#org.apache.solr.client.solrj.beans.Field("attr_name")
private String name;
#Column
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.YES)
#org.apache.solr.client.solrj.beans.Field("attr_value")
private String value;
.....
}
And my Spring Data Solr query interface:
public interface DerivedSubjectRepository extends SolrCrudRepository<PSubject, String> {
Page<PSubject> findByName(String name, Pageable page);
List<PSubject> findByNameStartingWith(String name);
Page<PSubject> findBy(Pageable page);
#Query("name:*?0* or description:*?0* or type:*?0* or mac_address:*?0* or uri:*?0* or attributes:*?0*")
Page<PSubject> find(String keyword,Pageable page);
#Query("name:*?0* or description:*?0* or type:*?0* or mac_address:*?0* or uri:*?0* or attributes:*?0*")
List<PSubject> find(String keyword);
}
I can search any by name, description, type and mac_address, but can't search any result by attribute.
Update:
For example,when user search "ipod", it's probably means the type of subject or name of subject, or the name of attribute or the value of attribute. And I want get all the matched subject in one request. I know I can search the attribute object in a separate query. But that makes the code in the backend complex.
So, how can I search this nested object?
Update:
I flattened my data:
#Transient
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
#org.apache.solr.client.solrj.beans.Field("attrs")
private String attrs;
public String getAttrs() {
return attrs;
}
public void setAttrs(Set<PAttribute> attributes) {
StringBuffer attrs = new StringBuffer();
if(attributes==null) {
attributes = this.getAttributes();
}
for(PAttribute attr:attributes){
attrs.append(attr.getName()+" " + attr.getValue()).append(" ");
}
this.attrs =attrs.toString();
}
The issue is resolved.
IIRC it is not possible to store nested data structures in solr - it depends how you flatten your data to fit into an eg. multivalue field - a little hard not knowing your schema.
see: http://lucene.472066.n3.nabble.com/Possible-to-have-Solr-documents-with-deeply-nested-data-structures-i-e-hashes-within-hashes-td4004285.html
How does the data look like in you index, and did you have a look at the http request sent by spring-data-solr?

Resources