Hi is there a way where we can do this via HQL??
where it returns me list of DTO instead of list of Object Class.
My sql query is
select * from readings join
(select max(signal) as signal,sender as sr ,receiver as rc from readings group by readings.sender,readings.receiver)a
on
a.signal=readings.signal and
a.sr=readings.sender and
a.rc=readings.receiver
Here is my DTO/Bean/Pojo class
public class Readings implements java.io.Serializable {
private Integer id;
private String sender;
private String major;
private String minor;
private int signal;
private BigDecimal power;
private BigDecimal temperature;
private String battery;
private String receiver;
private Date createdDatetime;..
and getters and setters ...
Which in HQL is
Criteria cr = session.createCriteria(com.XYZ..Readings.class)
.setProjection(Projections.projectionList()
.add(Projections.max("signal"))
.add(Projections.groupProperty("sender"))
.add(Projections.groupProperty("receiver")));
List<Readings> br=(List<Readings>)cr.list();
This fails at the last line, trying to cast Object to Readings class.
Related
I was trying out Spring ExampleMatcher for creating a query that requires use of in clause and between clause.
public class A{
private Long id;
private B b;
private D d;
private Date created;
}
public class B {
private Long id;
private C c;
private Long sequence;
}
public class C {
private Long id;
private String externalName;
}
public class D {
private Long id;
}
I need to create a query that matches in clause on A.b.c.externalName, equal clause on A.d.id and between operator on A.b.sequence fields.
Is it possible to do create a query using ExampleMatcher that fulfills above scenario.
Sample HQL : SELECT a FROM A a WHERE a.d.id = :subscriberId AND a.b.c.externalName IN :externalNames and a.b.sequence between (:startSequence, :endSequence)
Please help !
I have a DDBB with three tables: loan, person and loan_person_rel and the respective POJO for each table.
Loan
private int line;
private Double balance;
private Double expired;
private int state;
private int defaultDays;
private Branch branch;
private String balanceHistory;
private String expiredHistory;
private Long loanCode;
private List<Person> persons;
private String extraInfo;
private LoanTypes loanType;
private String nomPro;
//The class contains the getters and setters :)
Person
private String name;
private String documentNumber;
private String workEnterprise;
private String workCity;
private String workAddress;
private String workNeighborhood;
private String workPhone;
private String occupation;
private String homePhone;
private String cellPhone;
private String phone3;
private String phone4;
private String homeAddress;
private String homeCity;
private String homeNeighborhood;
private String email;
private String relationship;
private List<Loan> loans;
//The class contains the getters and setters :)
Loan_person_rel
private String personId;
private String loanId;
private int type;
//The class contains the getters and setters :)
How i can build a JOOQ select or some method for retrieve the data and fill the class loan with the field persons populated?
jOOQ 3.15 solutoin using MULTISET
Starting with jOOQ 3.15, the standard SQL MULTISET operator was introduced, which is emulated using SQL/XML or SQL/JSON if needed. For simplicity, I'm assuming your Loan and Person classes are Java 16 records:
List<Loan> result =
ctx.select(
// Project the loan columns you need
LOAN.LINE,
LOAN.BALANCE,
..
multiset(
select(PERSON.NAME, PERSON.DOCUMENT_NUMBER, ...)
.from(PERSON)
.join(LOAN_PERSON_REL)
.on(PERSON.PERSON_ID.eq(LOAN.PERSON_REL.PERSON_ID))
.where(LOAN_PERSON_REL.LOAN_ID.eq(LOAN.LOAN_ID))
).as("persons").convertFrom(r -> r.map(Records.mapping(Person::new)))
)
.from(LOAN)
.fetch(Records.mapping(Loan::new));
The mapping into the Loan and Person constructor references is type safe and reflection free, using the new jOOQ 3.15 ad-hoc converter feature.
Unlike JPA based ORMs, jOOQ doesn't offer object graph persistence, i.e. your Person objects can't contain identity-based references back to Loan objects. Instead, this approach projects data in tree form, which may be fine for your use-cases.
jOOQ 3.14 solution using SQL/XML or SQL/JSON
Starting with jOOQ 3.14, the preferred approach here is to nest your collections directly in SQL using SQL/XML or SQL/JSON. You could write a query like this:
List<Loan> result =
ctx.select(
// Project the loan columns you need, or all of them using LOAN.asterisk()
LOAN.LINE,
LOAN.BALANCE,
...
field(select(
jsonArrayAgg(jsonObject(
key("name").value(PERSON.NAME),
key("documentNumber").value(PERSON.DOCUMENT_NUMBER),
...
))
.from(PERSON)
.join(LOAN_PERSON_REL)
.on(PERSON.PERSON_ID.eq(LOAN.PERSON_REL.PERSON_ID))
.where(LOAN_PERSON_REL.LOAN_ID.eq(LOAN.LOAN_ID))
)).as("persons")
)
.from(LOAN)
.fetchInto(Loan.class);
The same restriction about this fetching trees instead of graphs applies.
Note that JSON_ARRAYAGG() aggregates empty sets into NULL, not into an empty []. If that's a problem, use COALESCE()
It must be so way:
List<Loan*> list = dsl.selectFrom(Loan).fetch(this::recordToPojo);
private Loan recordToPojo(final LoanRecord record) {
return new Loan(
record.getLine(),
record.getBalance(),
....
);
}
*Loan - name of pojo!
I'm having an issue performing a custom query through the use of a spring data jpa repository.
I have a repository class implementing JPARepository<>. Everything works as expected for all of the built-in CRUD queries along with some custom queries, but doing qualification among inner collections isn't working and is returning back a full result set as though the qualification of the collection did not exist.
For example, here is a query:
public interface MessageRepository extends JpaRepository<Message, Integer> {
#Query("SELECT a FROM Message a, Message_Topic b WHERE a.systemNm = :theSystem AND a. applicationNm = :theApplication AND b.topicNm = :theTopicName AND a.insertTs BETWEEN :theStartDate AND :theEndDate AND a.expirationDt > CURRENT_TIMESTAMP")
List<Message> findMessagesByTopic(#Param("theSystem") String theSystem,
#Param("theApplication") String theApplication,
#Param("theTopicName") String theTopicName,
#Param("theStartDate") Date theStartDate,
#Param("theEndDate") Date theEndDate);
With the following JPA entities:
Message:
#Entity
public class Message implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="message_id")
private int messageId;
#Column(name="application_nm")
private String applicationNm;
#Column(name="execution_instance_txt")
private String executionInstanceTxt;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="expiration_dt")
private Date expirationDt;
#Column(name="grouping_des")
private String groupingDes;
#Temporal(TemporalType.TIMESTAMP)
#Column(name="insert_ts")
private Date insertTs;
#Column(name="message_detail_txt")
private String messageDetailTxt;
#Column(name="message_summary_txt")
private String messageSummaryTxt;
#Column(name="severity_des")
private String severityDes;
#Column(name="system_nm")
private String systemNm;
//uni-directional many-to-one association to Message_Topic
#OneToMany(fetch=FetchType.EAGER)
#JoinColumn(name="message_id", referencedColumnName="message_id")
private Set<Message_Topic> messageTopics;
Message_Topic:
#Entity
public class Message_Topic implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="message_topic_id")
private int messageTopicId;
#Column(name="message_id", insertable=false, updatable=false)
private int messageId;
#Column(name="topic_nm")
private String topicNm;
#Column(name="topic_value_txt")
private String topicValueTxt;
This is your query:
SELECT a FROM Message a, Message_Topic b WHERE a.systemNm = :theSystem AND a. applicationNm = :theApplication AND b.topicNm = :theTopicName AND a.insertTs BETWEEN :theStartDate AND :theEndDate AND a.expirationDt > CURRENT_TIMESTAMP
Where are Message and Message_Topic joined?, If you transform this query to a native query, is possible you can detect the fault.
Lets say I have this two bean entities:
public class Audit {
private String code;
private java.sql.Timestamp creationDate;
private String creatorId;
private java.sql.Timestamp deletionDate;
private String description;
private String id;
private String name;
private String notes;
private Short status;
private List<AuditParticipant> participants;
}
and :
public class AuditParticipant {
private String auditId;
private String department;
private String id;
private String name;
private String notes;
private String role;
private String surname;
}
... where Audit can have 1..n Participants, how can I use QueryDSL SQL to project the list of the participants into Audit bean (get all participants that belongs to audit)?
The beans were generated using QueryDSL code generation.
Thanks
Querydsl provides result aggregation functionality for such cases http://www.querydsl.com/static/querydsl/3.1.1/reference/html/ch03s02.html#d0e1634
In this case it would be something like
query.from(audit)
.innerJoin(participant).on(...)
.transform(groupBy(audit.id).as(audit, list(participant)));
See these examples for other groupBy options https://github.com/mysema/querydsl/blob/master/querydsl-collections/src/test/java/com/mysema/query/collections/GroupByTest.java
I have a ArrayList which of type empDetail (a POJO class).
List<EmpDetail> empDetailList = new ArrayList<EmpDetail>();
This list represents a table in the database.
I need values for a dropdown list and so I did
<s:select list="empDetailList" listKey="country" listValue="country" name="country"></s:select>
By this I get all rows of country column from database and its good. But I need unique country in this dropdown list.
I know I can write a SQL query to get distinct country, but how to do it in this kind of scenario.
Update 1:
Do any one of you have Hibernate solution for this?
Update 2:
My POJO class as follows...
package bean;
import java.io.Serializable;
import java.sql.Date;
public class EmpDetail implements Serializable{
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private int age;
private String address;
private String city;
private String section;
private String country;
private String classStudying;
private String fatherName;
private String motherNmae;
private Date DOJ;
private String certificates;
private Date CompletedDate;
private String crossCheckedBy;
private Date crossCheckedDate;
private String comments;
//and its getters and setters...
}
You need to group by country objects. Simple HQL query
from EmpDetail where id in (select max(id) from EmpDetail group by country)
If you want to display distinct select items means
EmpDetail empDetail = new EmpDetail();
Map<Object, Object> empDetailMap = new LinkedHashMap<Object, Object>();
if (empDetailList.size() > 0) {
for (Iterator<EmpDetail> iter = industryDetail.iterator(); iter.hasNext();) {
empDetail = (EmpDetail) iter.next();
empDetailMap.put(empDetail.getId(),empDetail.getName());
}
}