I have a strange problem with JPA. In my sheduler executing next code
#SuppressWarnings("unchecked")
#Transactional
public void refreshSmsStatuses() {
try {
log.info("Enter refreshSmsStatuses");
EntityManager em = hibernateHelper.getEntityManager();
log.info("EM created");
List<Sms> lSms = null;
log.info("lSms = null;");
TypedQuery<Sms> smsQuery = em.createQuery(
"SELECT sms FROM Sms AS sms
join sms.status as status
WHERE status.isFinal = 0
and sms.remoteId is not null
and sms.sendDate > sysdate - 3", Sms.class);
log.info("sqlQuery created");
lSms = smsQuery.getResultList();
log.info("Query SMS executed");
.....
After planning nighty reboot it works several times and hangs. There are next strings
2018-12-17 00:10:33,802 [SmsDao.java:pool-2-thread-1:166] - lSms = null;
2018-12-17 00:10:33,802 [SmsDao.java:pool-2-thread-1:168] - sqlQuery created
in log files. The query does not execute in DB, it hangs somewhere in JPA. Problem is on only production server. After hanging any sheduler's methods don't work, because, I think they wait for the end of this method.
If anybody run into with similar problem, please help me.
Thanks a lot
UPDATED
#Table( name = "ZUSB_SMS")
#Entity
public class Sms extends BaseModel {
private static final long serialVersionUID = -3624326750555670797L;
#Id
#SequenceGenerator(name = "generator", sequenceName = "ZUSB_SMS_SEQ")
#GeneratedValue(strategy = GenerationType.AUTO, generator = "generator")
#Column(name = "id")
private Long id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "REF_SMS_TEMPLATE_ID", referencedColumnName = "id")
private SmsTemplate template;
#Column(name = "name")
private String name;
#Column(name = "send_date")
private Date sendDate;
#Column(name = "phone")
private String phone;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "REF_CLIENT_ID", referencedColumnName = "id")
private Client client;
#Column(name = "text")
private String text;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "REF_SMS_STATUS_ID", referencedColumnName = "id")
private SmsStatus status;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "REF_USER_ID", referencedColumnName = "id")
private User user;
#Column(name = "remote_id")
private Long remoteId;
private String log = "";
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "REF_CLE_STATUS_ID", referencedColumnName = "id")
private SmsCleStatus cleStatus;
#Column(name = "cle_text")
private String cleText;
#Column(name = "cle_id")
private Long cleId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public SmsTemplate getTemplate() {
return template;
}
public void setTemplate(SmsTemplate template) {
this.template = template;
}
public Date getSendDate() {
return sendDate;
}
public void setSendDate(Date sendDate) {
this.sendDate = sendDate;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public SmsStatus getStatus() {
return status;
}
public void setStatus(SmsStatus status) {
this.status = status;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Long getRemoteId() {
return remoteId;
}
public void setRemoteId(Long remoteId) {
this.remoteId = remoteId;
}
public String getLog() {
return log;
}
public void setLog(String log) {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date today = Calendar.getInstance().getTime();
String reportDate = df.format(today);
if(log.equals(""))
this.log = reportDate + " " + log;
else
this.log = this.log + "\n" + reportDate + " " + log;
}
public SmsCleStatus getCleStatus() {
return cleStatus;
}
public void setCleStatus(SmsCleStatus cleStatus) {
this.cleStatus = cleStatus;
}
public String getCleText() {
return cleText;
}
public void setCleText(String cleText) {
this.cleText = cleText;
}
public Long getCleId() {
return cleId;
}
public void setCleId(Long cleId) {
this.cleId = cleId;
}
}
P.S. Sorry for my English
First, your query is not correct since you didn't specify ON what you are joining. Second, You don't need to join SmsStatus table explicitly since you mapped it with #ManyToOne.
Update your query like this-
TypedQuery<Sms> smsQuery = em.createQuery(
"FROM Sms s
WHERE s.status.isFinal = 0
AND s.remoteId IS NOT NULL
AND s.sendDate > sysdate-3", Sms.class);
This may solve the problem.
Related
good day everyone,
i have this project where i use the ModelMapper to mat my entities to DTOs and vise-versa, and also have a class with #ElementCollection relation.
the mapper seems to work fine for all other methods and it just output the entity as i want, however when it comes to delete mapping i get the following error printed along with a 500 http status. here's the error:
"ModelMapper mapping errors:\r\n\r\n1) Converter org.modelmapper.internal.converter.CollectionConverter#ddb7bc7 failed to convert java.util.List to java.util.List.\r\n\r\n1 error"
here is code:
the entity class:
#Entity
#Table(name = "quiz_engines")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(
value = {"lastModified"},
allowGetters = true
)
public class Engine implements Model {
#Id
#Column(name = "engine_id", unique = true, nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne(fetch = FetchType.LAZY,optional = false, targetEntity = com.QCMGenerator.QCMGenerator.Model.Test.class)
#JoinColumn(name = "test_id", referencedColumnName = "test_id", nullable = false, updatable = false)
#OnDelete(action = OnDeleteAction.NO_ACTION)
#JsonIgnore
private Test test;
#Column(name = "quiz_name", nullable = false)
#NotNull
private String name;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "last_modified", nullable = false)
#LastModifiedDate
private Date lastModified;
#ElementCollection
#CollectionTable(name = "engine_constraints", joinColumns = #JoinColumn(name = "engine_id"))
private List<EngineConstraint> constraints;
public Engine() {
}
public Engine(#NotNull String name, List<EngineConstraint> constraints) {
this.name = name;
this.constraints = constraints;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Test getTest() {
return test;
}
public void setTest(Test test) {
this.test = test;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public List<EngineConstraint> getConstraints() {
return constraints;
}
public void setConstraints(List<EngineConstraint> constraints) {
this.constraints = constraints;
}
}
the DTO class:
public class EngineDTO implements ModelDTO {
private Long id;
#JsonIgnore
private TestDTO test;
private String name;
private Date lastModified;
private List<EngineConstraint> constraints;
public EngineDTO() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public TestDTO getTest() {
return test;
}
public void setTest(TestDTO test) {
this.test = test;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public List<EngineConstraint> getConstraints() {
return constraints;
}
public void setConstraints(List<EngineConstraint> constraints) {
this.constraints = constraints;
}
}
the Delete Controller:
#DeleteMapping("/{engineID}")
public ResponseEntity<NonPaginatedResponse> deleteEngine(
#PathVariable(value = "testID") Long testID,
#PathVariable(value = "engineID") Long engineID
){
if(!testRepo.existsById(testID)){
throw new ResourceNotFoundException("No test with the ID '"+testID+"' was found...");
}
return engineRepo.findById(engineID).map(engineFound -> {
engineRepo.delete(engineFound);
return ResponseEntity.status(HttpStatus.OK).body(
ResponseBodyBuilder.getSingleResponse(
convertToDTO(engineFound),
new ModelDTO[]{ convertToDTO(testRepo.findById(testID).get()) },
"delete"
)
);
}
).orElseThrow(
() -> new ResourceNotFoundException("No Engine with the ID '"+engineID+"' was found...")
);
}
hope you guys can help with this one, thank for your time everyone and have a good day.
Im getting the following error:
{"timestamp":1535929757444,"status":500,"error":"Internal Server Error","exception":"org.springframework.dao.DataIntegrityViolationException","message":"could not execute statement; SQL [n/a]; constraint [\"PRIMARY KEY ON PUBLIC.WT_TASK(TASK_ID)\"; SQL statement:\ninsert into wt_task (exercise_id, task_id) values (?, ?) [23505-196]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement","path":"/api/word-transformation/new"}
I was able to create a service to fetch JSON from the database but I cant manage to upload them.
This is my service:
public WordTransformationExercise save(WordTransformationExerciseRequest wtRequest) {
WordTransformationExercise wordTransformation = new WordTransformationExercise();
wordTransformation.setAuthorId(wtRequest.getAuthor_id());
List<WordTransformationTaskRequest> testP = wtRequest.getwt_task();
List<WordTransformation> thisIsIt = new ArrayList<WordTransformation>();
for(WordTransformationTaskRequest task : testP) {
WordTransformation send = new WordTransformation();
send.setBody(task.getBody());
send.setResult(task.getResult());
send.setWord(task.getWord());
send.setWordAtIndex(task.getWord_at_index());
thisIsIt.add(send);
}
wordTransformation.setwt_task(thisIsIt);
this.wtRepository.save(wordTransformation);
return wordTransformation;
}
This is my Entity:
#Entity
#Table(name = "wt_exercise")
public class WordTransformationExercise implements Serializable {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "author_id")
private Long authorId;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "wt_task",
joinColumns = #JoinColumn(name = "exercise_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "task_id", referencedColumnName = "task_id"))
private List<WordTransformation> wt_task;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getAuthorId() {
return authorId;
}
public void setAuthorId(Long authorId) {
this.authorId = authorId;
}
public void setwt_task(List<WordTransformation> list) {
this.wt_task = list;
}
public Collection<?> getwt_task() {
return this.wt_task;
}
}
This is Task entity:
#Entity
#Table(name = "wt_task")
public class WordTransformation implements Serializable {
#Id
#Column(name = "task_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long task_id;
#Column(name = "body")
private String body;
#Column(name = "result")
private String result;
#Column(name = "word")
private String word;
#Column(name = "word_at_index")
private Integer wordAtIndex;
#Column(name = "exercise_id")
private Long exercise_id;
public void setExercise_id(Long exercise_id) {
this.exercise_id = exercise_id;
}
public Long getExercise_id() {
return exercise_id;
}
public void setId(Long task_id) {
this.task_id = task_id;
}
public Long getId() {
return task_id;
}
public void setBody(String body) {
this.body = body;
}
public String getBody() {
return body;
}
public void setResult(String result) {
this.result = result;
}
public String getResult() {
return result;
}
public void setWord(String word) {
this.word = word;
}
public String getWord() {
return word;
}
public void setWordAtIndex(Integer wordAtIndex) {
this.wordAtIndex = wordAtIndex;
}
public Integer getWordAtIndex() {
return wordAtIndex;
}
}
My API is returning 'id' and 'authorId' fine when I set wt_task to null
This is an example of my sql:
INSERT INTO wt_exercise (id, author_id) VALUES (2, 2);
INSERT INTO wt_task (body, result, word, word_at_index, exercise_id, task_id) VALUES ('please start ', 'running', 'run', 13, 2, 2);
It depends on what you are trying to do.
If you are trying to update an existing entity, you should retrieve it from your repository and set the values instead of creating a new object and trying to save it with an existing key.
If you are trying to create something new then don't set the key at all.
I need to save the child table values without retrieve the values.
POJO Class:
public class User {
private String firstName;
#Id
#SequenceGenerator(name = "userID", sequenceName = "userID")
#GeneratedValue(strategy = GenerationType.AUTO, generator = "userID")
#Column(name = "id")
private Long id;
private String lastName;
private Integer passwordReset;
#Column(name = "useremail", nullable = false, unique = true)
#Email
#NotEmpty
private String email;
#Column(name = "password", nullable = false)
private String password;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "user_id", referencedColumnName = "id")
private List<WashingOrder> orderList;
#Column(unique = true)
#NotEmpty(message = "{username}")
private String username;
public String getFirstName() {
return firstName;
}
public Long getId() {
return id;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setId(Long id) {
this.id = id;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setPassword(String password) {
this.password = password;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getPasswordReset() {
return passwordReset;
}
public void setPasswordReset(Integer passwordReset) {
this.passwordReset = passwordReset;
}
public List<WashingOrder> getOrderList() {
return orderList;
}
public void setOrderList(List<WashingOrder> orderList) {
this.orderList = orderList;
}
}
public class WashingOrder {
#Id
#SequenceGenerator(name = "orderNo", sequenceName = "orderNo")
#GeneratedValue(strategy = GenerationType.AUTO, generator = "orderNo")
#Column(name = "orderNo")
private Long orderNo;
#Column(name = "totalClothes", nullable = false)
#NotNull
private Integer totalClothes;
#Column(name = "mensCloth", nullable = true)
private Integer mensCloth;
#Column(name = "womensCloth", nullable = true)
private Integer womensCloth;
#Column(name = "otherCloth", nullable = true)
private Integer otherClothes;
#Column(name = "deliveryDate", nullable = true)
/* #DateTimeFormat(pattern = "yyyy-mm-dd") */
private Date deliveryDate;
#Column(name = "status", nullable = true)
private String orderStatus;
public Long getOrderNo() {
return orderNo;
}
public void setOrderNo(Long orderNo) {
this.orderNo = orderNo;
}
public Integer getTotalClothes() {
return totalClothes;
}
public void setTotalClothes(Integer totalClothes) {
this.totalClothes = totalClothes;
}
public Integer getMensCloth() {
return mensCloth;
}
public void setMensCloth(Integer mensCloth) {
this.mensCloth = mensCloth;
}
public Integer getWomensCloth() {
return womensCloth;
}
public void setWomensCloth(Integer womensCloth) {
this.womensCloth = womensCloth;
}
public Integer getOtherClothes() {
return otherClothes;
}
public void setOtherClothes(Integer otherClothes) {
this.otherClothes = otherClothes;
}
public Date getDeliveryDate() {
return deliveryDate;
}
public void setDeliveryDate(Date deliveryDate) {
this.deliveryDate = deliveryDate;
}
public String getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
}
Implementation:
Session session = sessionFactory.getCurrentSession();
long id = 1;
Query query = session.createQuery("from user where id =" + id);
User emp6 = (User) session.load(User.class, new Long(1));
User user = (User) query.uniqueResult();
List<WashingOrder> washingOrder = user.getOrderList();
washingOrder.add(order);
user.setOrderList(washingOrder);
session.save(user);
Long orderID = (long) 1;
return orderID;
Here if you check I am getting the order list first (user.getOrderList()) and then I am adding the new list and saving the user.
But I want to save the new order list of the user without retrieve the previous order list.
There is any possibility for the adding new order data without retrieve the previous order list of the particular user.
You need to change a mapping
public class User {
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<WashingOrder> orderList;
}
public class WashingOrder {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id")
private User user;
}
Session session = sessionFactory.getCurrentSession();
User user = (User) session.load(User.class, 1L);
WashingOrder order = new WashingOrder();
order.setUser(user);
session.save(order);
You can try to use a fake User instead of loading
WashingOrder order = new WashingOrder();
order.setUser(new User(1L));
session.save(order);
I searched lot. But can't find solution for my case. i want create hibernate criteria for following query.
SELECT * FROM patient as p1 LEFT OUTER JOIN (SELECT * FROM patient_caller_admin_map WHERE caller_admin_id='1') as pca ON p1.patient_id=pca.patient_id;
i went through the DetachedCriteria , Criteria and created the following things. But don't know how to use LEFT_JOIN by joining both.
DetachedCriteria inner=DetachedCriteria.forClass(PatientCallerAdminMap.class, "patientCallerAdmin");
Criteria cr1=this.sessionFactory.getCurrentSession().createCriteria(Patient.class,"patient");
PatientCallerAdminMap Entity:
/**
* PatientCallerAdminMap generated by hbm2java
*/
#Entity
#Table(name = "patient_caller_admin_map", catalog = "test")
public class PatientCallerAdminMap implements java.io.Serializable {
private PatientCallerAdminMapId id;
private CallerAdmin callerAdmin;
private Caller caller;
private Patient patient;
private String notes;
private Integer isArchived;
private Integer patientStatus;
private Set<CallLog> callLogs = new HashSet<CallLog>(0);
private Set<CallLog> callLogs_1 = new HashSet<CallLog>(0);
public PatientCallerAdminMap() {
}
public PatientCallerAdminMap(PatientCallerAdminMapId id,
CallerAdmin callerAdmin, Patient patient) {
this.id = id;
this.callerAdmin = callerAdmin;
this.patient = patient;
}
public PatientCallerAdminMap(PatientCallerAdminMapId id,
CallerAdmin callerAdmin, Caller caller, Patient patient,
String notes, Integer isArchived, Integer patientStatus,
Set<CallLog> callLogs, Set<CallLog> callLogs_1) {
this.id = id;
this.callerAdmin = callerAdmin;
this.caller = caller;
this.patient = patient;
this.notes = notes;
this.isArchived = isArchived;
this.patientStatus = patientStatus;
this.callLogs = callLogs;
this.callLogs_1 = callLogs_1;
}
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "patientId", column = #Column(name = "patient_id", nullable = false)),
#AttributeOverride(name = "callerAdminId", column = #Column(name = "caller_admin_id", nullable = false)) })
public PatientCallerAdminMapId getId() {
return this.id;
}
public void setId(PatientCallerAdminMapId id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "caller_admin_id", nullable = false, insertable = false, updatable = false)
public CallerAdmin getCallerAdmin() {
return this.callerAdmin;
}
public void setCallerAdmin(CallerAdmin callerAdmin) {
this.callerAdmin = callerAdmin;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "caller_id")
public Caller getCaller() {
return this.caller;
}
public void setCaller(Caller caller) {
this.caller = caller;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "patient_id", nullable = false, insertable = false, updatable = false)
public Patient getPatient() {
return this.patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
#Column(name = "notes", length = 600)
public String getNotes() {
return this.notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
#Column(name = "is_archived")
public Integer getIsArchived() {
return this.isArchived;
}
public void setIsArchived(Integer isArchived) {
this.isArchived = isArchived;
}
#Column(name = "patient_status")
public Integer getPatientStatus() {
return this.patientStatus;
}
public void setPatientStatus(Integer patientStatus) {
this.patientStatus = patientStatus;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "patientCallerAdminMap")
public Set<CallLog> getCallLogs() {
return this.callLogs;
}
public void setCallLogs(Set<CallLog> callLogs) {
this.callLogs = callLogs;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "patientCallerAdminMap")
public Set<CallLog> getCallLogs_1() {
return this.callLogs_1;
}
public void setCallLogs_1(Set<CallLog> callLogs_1) {
this.callLogs_1 = callLogs_1;
}
}
Patient Entity Class:
#Entity
#Table(name = "patient", catalog = "test")
public class Patient implements java.io.Serializable {
private String patientId;
private String addedDate;
private String name;
private String dateOfBirth;
private String gender;
private String address;
private String phoneNumber;
private Integer tier;
private Integer patientStatus;
private Integer status;
private Set<PatientCallerAdminMap> patientCallerAdminMaps = new HashSet<PatientCallerAdminMap>(
0);
public Patient() {
}
public Patient(String patientId) {
this.patientId = patientId;
}
public Patient(String patientId,String addedDate, String timeOfCrash,
String name, String dateOfBirth, String gender,
String address,
String phoneNumber,Integer tier, Integer patientStatus,
Integer status,
Set<PatientCallerAdminMap> patientCallerAdminMaps,
) {
this.patientId = patientId;
this.addedDate = addedDate;
this.name = name;
this.dateOfBirth = dateOfBirth;
this.gender = gender;
this.address = address;
this.phoneNumber = phoneNumber;
this.tier=tier;
this.patientStatus = patientStatus;
this.status = status;
this.patientCallerAdminMaps = patientCallerAdminMaps;
}
#Id
#Column(name = "patient_id", unique = true, nullable = false)
public String getPatientId() {
return this.patientId;
}
public void setPatientId(String patientId) {
this.patientId = patientId;
}
#Column(name = "added_date", length = 45)
public String getAddedDate() {
return addedDate;
}
public void setAddedDate(String addedDate) {
this.addedDate = addedDate;
}
#Column(name = "name", length = 100)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "date_of_birth", length = 45)
public String getDateOfBirth() {
return this.dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
#Column(name = "gender", length = 5)
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#Column(name = "address", length = 200)
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
#Column(name = "phone_number", length = 20)
public String getPhoneNumber() {
return this.phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
#Column(name = "tier")
public Integer getTier() {
return this.tier;
}
public void setTier(Integer tier) {
this.tier = tier;
}
#Column(name = "patient_status")
public Integer getPatientStatus() {
return this.patientStatus;
}
public void setPatientStatus(Integer patientStatus) {
this.patientStatus = patientStatus;
}
#Column(name = "status")
public Integer getStatus() {
return this.status;
}
public void setStatus(Integer status) {
this.status = status;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "patient")
public Set<PatientCallerAdminMap> getPatientCallerAdminMaps() {
return this.patientCallerAdminMaps;
}
public void setPatientCallerAdminMaps(
Set<PatientCallerAdminMap> patientCallerAdminMaps) {
this.patientCallerAdminMaps = patientCallerAdminMaps;
}
}
Please help to solve this.
Maybe you can achieve this without using subquery so the query become simpler :
Criteria cr1=this.sessionFactory.getCurrentSession().createCriteria(Patient.class,"patient");
cr2=cr1.createCriteria("patientCallerAdminMaps ",CriteriaSpecification.LEFT_JOIN);
cr3= cr2.createCriteria("callerAdmin",CriteriaSpecification.LEFT_JOIN);
cr3.add(Restrictions.eq("id", "1"));
For the "select *" you can't do it with criteria. This criteria will return a list of Patient entity.
If really want * you will have to add alias on subcriteria and use Projection to select explicitly the fields that you want
I have a question about Subquery class in jpa.
I need to create subquery with two custom field, but subquery doesn't have multiselect method and select method has Expression input parameter(In query this is Selection) and constact method not suitable.
Also I have question about join subquery results, It is possible? And how to?
I have:
Chain Enitity
public class Chain {
#Id
#Column(name = "chain_id")
#GeneratedValue(generator = "seq_cha_id", strategy = GenerationType.SEQUENCE)
#SequenceGenerator(name = "seq_cha_id", sequenceName = "SEQ_CHA_ID", allocationSize = 1)
private Long id;
#Column(name = "user_id")
private Long userId;
#Column(name = "operator_id")
private Long operatorId;
#Column(name = "subject")
private String subject;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "chain")
private List<Message> messages;
#Column(name = "status")
private Status status;
public Long getOperatorId() {
return operatorId;
}
public void setOperatorId(Long operatorId) {
this.operatorId = operatorId;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSubject() {
return subject;
}
public void setSubject(String theme) {
this.subject = theme;
}
public List<Message> getMessages() {
return messages;
}
public void setMessages(List<Message> messages) {
this.messages = messages;
}
}
Message Enitity
public class Message {
#Id
#Column(name = "message_id")
#GeneratedValue(generator = "seq_mess_id", strategy = GenerationType.SEQUENCE)
#SequenceGenerator(name = "seq_mess_id", sequenceName = "SEQ_MESS_ID", allocationSize = 1)
private Long id;
#Column(name = "user_id")
private Long userId;
#Column(name = "message", nullable = true, length = 4000)
private String message;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "chain_id")
private Chain chain;
#Column(name = "creation_date")
private Date date;
#Column(name = "status")
private Status status;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Chain getChain() {
return chain;
}
public void setChain(Chain chain) {
this.chain = chain;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
}
Wrapper for query
public class MessageWrapper {
private final Long chainId;
private final Long messageId;
public MessageWrapper(Long chainId, Long messageId) {
this.chainId = chainId;
this.messageId = messageId;
}
}
I need to create this query (this is part of query, another part I get from predicates. JPQL not suitable)
SELECT ch.*
FROM hl_chain ch,
(SELECT mes.chain_id,
max(message_id) message_id
FROM hl_message mes
GROUP BY chain_id) mes
WHERE mes.chain_id = ch.chain_id
ORDER BY message_id;
In Subquery I do
Subquery<MessageWrapper> subquery = criteriaQuery.subquery(MessageWrapper.class);
Root<Message> subRoot = subquery.from(Message.class);
subquery.select(cb.construct(
MessageWrapper.class,
subRoot.get(Message_.chain),
cb.max(subRoot.get(Message_.id))
));
But, the subquery doesn't have select with CompoundSelection in params and I can't use the CriteriaBuilder construct method.
A view on database mapped as an entity will do the job you need.
It is mapped as a normal table only with the tag #View instead.
I did the same on my projects.
You can call native queries from JPA, for example:
Query q = em.createNativeQuery("SELECT p.firstname, p.lastname FROM Person p");
List<Object[]> persons= q.getResultList();
for (Object[] p : persons) {
System.out.println("Person "
+ p[0]
+ " "
+ p[1]);
}
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<MessageWrapper> q = cb.createQuery(MessageWrapper.class);
Root<Chain> c = q.from(Chain.class);
Join<Chain, Message> m = p.join("messages");
q.groupBy(c.get("id"));
q.select(cb.construct(MessageWrapper.class, c.get("id"), cb.max(m.get("id"))));