JPQL Join and class cast exception - spring-boot

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

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.

Spring JPA Update Entity

I'm trying to update my user entity and I have an error that comes to mind:
ERROR: A NULL value violates the NOT NULL constraint of the "id" column Detail: The failed row contains (null, 1, 1)
The problem surely stems from my relationship between user and profile which is n-n
public class Utilisateur implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Integer id;
private Integer fixe;
private Boolean deleted;
private Boolean actif;
private String email;
private Integer mobile;
private String motDePasse;
private String nom;
private String prenom;
#ManyToMany
private List<Profil> profils = new ArrayList<Profil>();
public Utilisateur() {
}
}
public class Profil implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Integer id;
private String codeProfil;
private String libelleProfil;
#JsonManagedReference
#ManyToMany
private List<MenuAction> menuActions = new ArrayList<MenuAction>();
public Profil() {
}
}
How you generate value for your id?
Seems you need some way to generate value for you ID.
For example, use #GeneratedValue, like:
#GeneratedValue(strategy = IDENTITY)

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>

I want to create an entity X

I want to create an entity X with atributes.
Everything is right except the attribute "permissions" :
public class X implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long idNotateur;
#NotEmpty
private String nomNotateur;
#NotEmpty
private String prenomNotateur;
#NotEmpty
private String fonctionNotateur;
#NotEmpty
private String userNotateur;
#NotEmpty
private String passNotateur;
#ManyToOne
#JoinColumn(name="id_poste")
private Poste poste;
#ManyToOne
#JoinColumn(name="id_dir")
private Direction direction;
#OneToMany(mappedBy="notateur")
private Collection<Employe> Employes;
private Collection<Long> permissions;
getters & setters ...
public Collection<Long> getPermissions() {
return permissions;
}
public void setPermissions(Collection<Long> permissions) {
this.permissions = permissions;
}
}
Then I came across the following error: Caused by: org.hibernate.MappingException: Could not determine type for: java.util.Collection, at table: X, for columns: [org.hibernate.mapping.Column(permissions)]
So how to solve it?
I'm using Spring MVC Hibenate

Spring and Hibernate Error -- not-null property references a null or transient value: com.tharaka.model.Employee.designation

im new to Spring and hibernate, i got the error above when trying to persist the transaction data. please try to help this problem
Here's my Entity:
#Entity #NamedQuery(name="Employee.findAll", query="SELECT e FROM Employee e")
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String city;
private String civil;
#Temporal(TemporalType.DATE)
#Column(name="dob", length=11)
private Date dob;
private String email;
private int epf;
private String fname;
private String gender;
private int landtp;
private String lname;
#Temporal(TemporalType.DATE)
#Column(name="salaryincrement", length=11)
//bi-directional many-to-one association to Designation
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="designation_id", nullable=false)
private Designation designation;
public Employee() { }
#Entity
#NamedQuery(name="Designation.findAll", query="SELECT d FROM Designation d")
public class Designation implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String type;
//bi-directional many-to-one association to Employee
#OneToMany(mappedBy="designation")//, cascade=CascadeType.ALL
private List<Employee> employees;
public Designation() {
}
this is my Entity class,
Entities have a getters ans setters
designation is set nullable = false. However employees variable isn't initialized in Designation. So, you'll have to initialize as
#OneToMany(mappedBy="designation")//, cascade=CascadeType.ALL
private List<Employee> employees = new LinkedList<>();
I'm not sure that you can go with primitive type int as your Id - you should probably use Integer - because int has default zero value and cannot be null, your new record can be rather seen as a detached entity with Id ZERO and not as a transient one.
The same mistake is in Designation class.
See Primitive or wrapper for hibernate primary keys

Resources