Using Spring JPA Query to populate a pojo - spring

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.

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?

CQEngine Query nested object using parser.retrieve

I have a nested object like
public class SQSMessage implements Serializable {
private String type;
private boolean isEntity;
private String eventType;
private SystemInfo systemInfo;
private DomainAttributes domainAttributes;
#Data
public static class SystemInfo implements Serializable {
private String identifier;
private String ownedBy;
private Payload payload;
private EntityTags entityTags;
private long createdOn;
private String createdBy;
private long version;
private long lastUpdatedOn;
private String lastUpdatedBy;
private String attrEncKeyName;
#Data
public static class Payload implements Serializable {
private String bucketName;
private String objName;
private String encKeyName;
private byte[] payloadBytes;
private byte[] decryptedBytes;
private byte[] sanitizedBytes;
}
#Data
public static class EntityTags implements Serializable {
private List<Tag> tags;
#Data
public static class Tag implements Serializable {
private String tagName;
private String tagValue;
}
}
}
#Data
public static class DomainAttributes implements Serializable {
private String updatedByAuthId;
private String saveType;
private String docName;
private String ceDataType;
private String year;
private String appId;
private String formSetId;
private String appSku;
private String deviceId;
private String deviceName;
}
}
I would like to query the collection of SQSObjects by applying a filter like
ResultSet<SQSMessage> results = parser.retrieve(indexedSQSMessage, "SELECT * FROM indexedSQSMessage WHERE type='income' and DomainAttributes.saveType in ('endSession', 'cancelled')or (DomainAttributes.countryCode is null or DomainAttributes.countryCode='US'");
Is that possible using CQEngine? if yes.. please send me the examples.
The reason why I want o make that as sql... where clause is dynamic for various use cases.
Your example is more complicated than it needs to be for the question, so I am just skimming it. (Read about SSCCE)
However generally this kind of thing should be possible. See this related question/answer for how to construct nested queries: Can CQEngine query an object inside another object
If you set up attributes like that, you should be able to use them in SQL queries as well as programmatically.

Spring Web flux Mongo query

Hi I am new to Spring web flux and facing the issue regarding Mongo reactive query.
I have following structure of my model class
public class Users implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
private String id;
private String firstName;
private String middleName;
private String lastName;
private List<Email>emails;
}
public class Email implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
String address;
boolean verified;
}
Now I have to query that if given email exists or not in the mong document as email filed is list of email as given above.
Can any one please me on this?
I have written the following query on repository
#Query(value = "{'emails.address' : ?0 }")
Mono<Users> findByEmails(String address);
try using
#Query("{'users.emails.address': ?0}")
Mono <Users> findUserByEmailAddress(final String address)

JPQL Join and class cast exception

I am using JPA with Hibernate in spring boot.
I have two jpa entities
#Entity
#Table(name="courses_type")
public class CoursesType implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private int id;
#Column(name="course_id")
private int courseId;
#Column(name="level")
private int level;
private int credential;
private String status;
private String type;
#Column(name="updated_by")
private int updatedBy;
#Column(name="updated_on")
private Timestamp updatedOn;
#ManyToOne(fetch=FetchType.LAZY, optional=false)
#JoinColumn(name="credential", referencedColumnName="value_id",insertable=false,updatable=false)
#Where(clause="status='live'")
private BaseAttributeList credentialData;
#ManyToOne(fetch=FetchType.LAZY, optional=false)
#JoinColumn(name="level", referencedColumnName="value_id",insertable=false,updatable=false)
#Where(clause="status='live'")
private BaseAttributeList courseLevelData;
... setters and getters
}
Second Entity
#Entity
#Table(name="attribute_list")
public class AttributeList implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="value_id")
private int valueId;
private String status;
#Column(name="value_name")
private String valueName;
}
Now I am trying to write a JPQL Query in CourseTypeRepo
#Query("Select sct.courseId, sct.credential, sct.credentialData from CoursesType"
+ " sct where sct.courseId IN(?1) and sct.status = ?2")
List<CoursesType> getDataWithAttributes1(ArrayList<Integer> courseId, String status);
Now when I am iterating the result, I am getting class Cast Exception that
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.domain.CoursesType
Basically what I am trying to fetch the complete data using one jpql query.
How should I fix this?
If don't want to fetch full object but only some its properties you have to provide a projection then use it in your query method, for example:
public interface PartialCoursesType {
Integer getCourseId(),
Integer getCredential(),
BaseAttributeList getCredentialData()
}
#Query("select sct.courseId as courseId, sct.credential as credential, sct.credentialData as credentialData...")
List<PartialCoursesType> getDataWithAttributes1(ArrayList<Integer> courseId, String status);
To make the trick works you have to use aliases in the query...

Spring Data JPA Mapping Exception No Dialect mapping for JDBC type: -9

I am trying to use a projection and am getting the following error. Not sure what the issue is.
Here is the projection:
public interface UserMini {
Long getApproverKey();
String getEmailAddress();
String getFirstName();
String getLastName();
Long getUserKey();
String getUserName();
}
Here is the Query in the repository:
#RestResource(path="getUserMini")
#Query(value="SELECT approverKey, emailAddress, firstName, lastName, userKey, userName FROM [dbo].BdmUser WHERE userKey = :userKey ", nativeQuery=true)
UserMini getUserMini(#Param("userKey") long userKey);
Here is the Entity
#Table (name="[BdmUser]")
#Entity
public class BdmUser {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long userKey;
private Long priceListKey;
private String firstName;
private String lastName;
private String userName;
private String emailAddress;
private String password;
private Boolean active;
private Long approverKey;
private BigDecimal orderLimit;
private Long salesOfficeKey;
private Long reportsToId;
private Boolean requiresOrderApproval;
private Date lastLoginDate;
private String rowIsCurrent;
private Date rowStartDate;
private Date rowEndDate;
#Column(name="HashByteValueType1", updatable=false, insertable=false)
private String hashByteValueType1;
#Column(name="HashByteValueType2", updatable=false, insertable=false)
private String hashByteValueType2;
private String rowChangeReason;
#Column(name="DQScoreKey")
private Integer dqScoreKey;
private Integer insertAuditKey;
private Integer updateAuditKey;
Try to cast the NVARCHAR to VARCHAR in your query
CONVERT(varchar,theNVarcharColumn)

Resources