Redis - key consists of multiple fields - spring-boot

I use Spring Boot and I'd like to save these objects in redis:
#RedisHash("Myobj")
public class Trace implements Serializable {
#Id
#JsonProperty
private final String id;
#JsonProperty
private final TraceType type;
#JsonProperty
private final String clientId;
#JsonProperty
private final String topicId;
#JsonProperty
private final String url;
#JsonProperty
private final String payload;
#JsonProperty
private final Date date;
How can I store these objects and later get some values using the following query:
get all objects for the particular clientId from date date1 to date2.
I use
#Repository
public interface TraceRepository extends CrudRepository<Trace, String> {
to save data this way:
traceRepository.save(trace);
THANK YOU VERY MUCH IN ADVANCE! It's very important for me. Thank you.

Related

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.

How do I map polymorphic Java classes to MongoDB entities using Spring?

I am relatively new to Spring. I'm trying to implement a simple CRUD RESTful API for MongoDB. I'm having issues with mapping annotations when it comes to polymorphic classes.
Here's my Employee class that holds a list of Allocations. The idea is that an employee can have multiple allocations at once. An Allocation could either be a training or a department.
public class Employee {
#Id
private String id;
private String empCode;
private String firstName;
private String lastName;
private List<Allocation> allocations;
// Getters, setters and Constructor
}
Here's the Allocation class.
public class Allocation {
#Id
private String id;
private LocalDate startDate;
private LocalDate endDate;
private String location;
}
And here are the Department and Training classes.
public class Training extends Allocation {
#Id
private String id;
private String courseName;
}
public class Department extends Allocation {
#Id
private String id;
private String deptName;
}
How do I map the above classes using Spring annotations? When I retrieve an Employee, I want the JSON to have an array of Allocations that include both Training Programs and Departments.

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...

Persist LinkedHashMap in blob

I'm trying to persist a LinkedHashMap in a blob field of my db.
My entity looks as follows
#Entity
public class Event {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private long timestamp;
#Lob
private Map<String, Object> payload;
...
My repository looks as follows
#Repository
public interface EventRepositoryInterface extends CrudRepository<Event, Long> {
}
When trying to store my Event object I get the following error message
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to java.sql.Blob
Any clues about what's wrong?
BLOB is used for storing binary data, BLOB values are treated as binary strings (byte strings). They have no character set, and sorting and comparison are based on the numeric values of the bytes in column values.
I'll suggest that you use TEXT instead.
And also you must use JPA #EntityListeners or Callbacks Methods #PrePersist: and #PostLoad your code become
#Entity
public class Event {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private long timestamp;
#Column(columnDefinition = "TEXT")
private String payload
#Transient
private Map<String, Object> payloadOb;
#PrePersist
public payloadMapToText(){
this.payload = mapToString(this.payloadOb);
}
#PostLoad
public payloadTextToMap(){
this.payloadOb = stringToMap(this.payload);
}
}
You need to add more annotation to the mapping:
#Lob
#MapKeyColumn(name = "key_column")
#Column(name = "value_column")
#ElementCollection
private Map<String, Object> payload;
This is the needed setup, where the map is defined as Map<Basic, Basic>

Resources