I am trying to implement a simple HQL query of all objects of type A ordered by the following predicate :
a.getListB().get(0).getC().getLastname()
I tried the following HQL query :
select a_ from A a_ order by a_.listB.c.lastname
But I am getting the following exception :
org.hibernate.QueryException: illegal attempt to dereference collection
I have tried the following SQL query but I am getting inconsistent results :
select a.* from A a
left outer join B b on b.a_id=a.id
left outer join C c on b.uploaded_from=c.id
order by c.lastname=(select c_.lastname from A a_
left outer join B b_ on b_.a_id=a_.id
left outer join C c_ on b_.uploaded_from=c_.id
where a.id=a_.id limit 1) asc;
Code snipet :
#Entity
#Table(name = "A")
pubic class A {
private int id;
private List<B> listB;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
#OrderBy(clause = "id")
#OneToMany(fetch = FetchType.LAZY, mappedBy = "a")
public List<B> getListB() {
return this.listB;
}
}
#Entity
#Table(name = "B")
pubic class B {
private int id;
private A a;
private C c;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "a_id", nullable = false)
public A getA() {
return this.a;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "uploaded_from", nullable = false)
public C getC() {
return this.c;
}
}
#Entity
#Table(name = "C")
pubic class C {
private int id;
private String lastname;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
#Column(name = "lastname")
public String getLastname() {
return this.lastname;
}
}
Any hints how can I work around this problem please either in HQL, Criteria or even native SQL?
I used the following tables to test one possible solution for your problem further below
create table A (
id UUID
);
create table B (
id UUID,
id_a UUID,
id_c UUID
);
create table C (
id UUID,
lastname varchar(63)
);
insert into A values
('aaaaaaaa-aaaa-aaaa-aaaa-000000000000'),
('aaaaaaaa-aaaa-aaaa-aaaa-000000000001'),
('aaaaaaaa-aaaa-aaaa-aaaa-000000000002'),
('aaaaaaaa-aaaa-aaaa-aaaa-000000000003'),
('aaaaaaaa-aaaa-aaaa-aaaa-000000000004');
insert into C values
('cccccccc-cccc-cccc-cccc-000000000000', 'C zero'),
('cccccccc-cccc-cccc-cccc-000000000001', 'C one'),
('cccccccc-cccc-cccc-cccc-000000000002', 'C two'),
('cccccccc-cccc-cccc-cccc-000000000003', 'C three'),
('cccccccc-cccc-cccc-cccc-000000000004', 'C four'),
('cccccccc-cccc-cccc-cccc-000000000005', 'C five'),
('cccccccc-cccc-cccc-cccc-000000000006', 'C six');
insert into B values
('bbbbbbbb-bbbb-bbbb-bbbb-000000000000', 'aaaaaaaa-aaaa-aaaa-aaaa-000000000000', 'cccccccc-cccc-cccc-cccc-000000000000'),
('bbbbbbbb-bbbb-bbbb-bbbb-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-000000000000', 'cccccccc-cccc-cccc-cccc-000000000001'),
('bbbbbbbb-bbbb-bbbb-bbbb-000000000002', 'aaaaaaaa-aaaa-aaaa-aaaa-000000000000', 'cccccccc-cccc-cccc-cccc-000000000002'),
('bbbbbbbb-bbbb-bbbb-bbbb-000000000003', 'aaaaaaaa-aaaa-aaaa-aaaa-000000000001', 'cccccccc-cccc-cccc-cccc-000000000003'),
('bbbbbbbb-bbbb-bbbb-bbbb-000000000004', 'aaaaaaaa-aaaa-aaaa-aaaa-000000000001', 'cccccccc-cccc-cccc-cccc-000000000004'),
('bbbbbbbb-bbbb-bbbb-bbbb-000000000005', 'aaaaaaaa-aaaa-aaaa-aaaa-000000000001', 'cccccccc-cccc-cccc-cccc-000000000005'),
('bbbbbbbb-bbbb-bbbb-bbbb-000000000006', 'aaaaaaaa-aaaa-aaaa-aaaa-000000000002', 'cccccccc-cccc-cccc-cccc-000000000006'),
('bbbbbbbb-bbbb-bbbb-bbbb-000000000007', 'aaaaaaaa-aaaa-aaaa-aaaa-000000000002', 'cccccccc-cccc-cccc-cccc-000000000000'),
('bbbbbbbb-bbbb-bbbb-bbbb-000000000008', 'aaaaaaaa-aaaa-aaaa-aaaa-000000000002', 'cccccccc-cccc-cccc-cccc-000000000001'),
('bbbbbbbb-bbbb-bbbb-bbbb-000000000009', 'aaaaaaaa-aaaa-aaaa-aaaa-000000000003', 'cccccccc-cccc-cccc-cccc-000000000002'),
('bbbbbbbb-bbbb-bbbb-bbbb-000000000010', 'aaaaaaaa-aaaa-aaaa-aaaa-000000000003', 'cccccccc-cccc-cccc-cccc-000000000003'),
('bbbbbbbb-bbbb-bbbb-bbbb-000000000011', 'aaaaaaaa-aaaa-aaaa-aaaa-000000000003', 'cccccccc-cccc-cccc-cccc-000000000004'),
('bbbbbbbb-bbbb-bbbb-bbbb-000000000012', 'aaaaaaaa-aaaa-aaaa-aaaa-000000000004', 'cccccccc-cccc-cccc-cccc-000000000005'),
('bbbbbbbb-bbbb-bbbb-bbbb-000000000013', 'aaaaaaaa-aaaa-aaaa-aaaa-000000000004', 'cccccccc-cccc-cccc-cccc-000000000006'),
('bbbbbbbb-bbbb-bbbb-bbbb-000000000014', 'aaaaaaaa-aaaa-aaaa-aaaa-000000000004', 'cccccccc-cccc-cccc-cccc-000000000000'),
('bbbbbbbb-bbbb-bbbb-bbbb-000000000015', 'aaaaaaaa-aaaa-aaaa-aaaa-000000000000', 'cccccccc-cccc-cccc-cccc-000000000001'),
('bbbbbbbb-bbbb-bbbb-bbbb-000000000016', 'aaaaaaaa-aaaa-aaaa-aaaa-000000000001', 'cccccccc-cccc-cccc-cccc-000000000002'),
('bbbbbbbb-bbbb-bbbb-bbbb-000000000017', 'aaaaaaaa-aaaa-aaaa-aaaa-000000000002', 'cccccccc-cccc-cccc-cccc-000000000003');
Unique id_a entries are numbered via this intermediate select:
select id,id_a,id_c,ROW_NUMBER()
over (partition by id_a order by id_a) as rowNumber
from B as aggregate;
Result:
id | id_a | id_c | rownumber
--------------------------------------+--------------------------------------+--------------------------------------+-----------
bbbbbbbb-bbbb-bbbb-bbbb-000000000000 | aaaaaaaa-aaaa-aaaa-aaaa-000000000000 | cccccccc-cccc-cccc-cccc-000000000000 | 1
bbbbbbbb-bbbb-bbbb-bbbb-000000000015 | aaaaaaaa-aaaa-aaaa-aaaa-000000000000 | cccccccc-cccc-cccc-cccc-000000000001 | 2
bbbbbbbb-bbbb-bbbb-bbbb-000000000001 | aaaaaaaa-aaaa-aaaa-aaaa-000000000000 | cccccccc-cccc-cccc-cccc-000000000001 | 3
bbbbbbbb-bbbb-bbbb-bbbb-000000000002 | aaaaaaaa-aaaa-aaaa-aaaa-000000000000 | cccccccc-cccc-cccc-cccc-000000000002 | 4
bbbbbbbb-bbbb-bbbb-bbbb-000000000004 | aaaaaaaa-aaaa-aaaa-aaaa-000000000001 | cccccccc-cccc-cccc-cccc-000000000004 | 1
bbbbbbbb-bbbb-bbbb-bbbb-000000000016 | aaaaaaaa-aaaa-aaaa-aaaa-000000000001 | cccccccc-cccc-cccc-cccc-000000000002 | 2
bbbbbbbb-bbbb-bbbb-bbbb-000000000003 | aaaaaaaa-aaaa-aaaa-aaaa-000000000001 | cccccccc-cccc-cccc-cccc-000000000003 | 3
bbbbbbbb-bbbb-bbbb-bbbb-000000000005 | aaaaaaaa-aaaa-aaaa-aaaa-000000000001 | cccccccc-cccc-cccc-cccc-000000000005 | 4
bbbbbbbb-bbbb-bbbb-bbbb-000000000017 | aaaaaaaa-aaaa-aaaa-aaaa-000000000002 | cccccccc-cccc-cccc-cccc-000000000003 | 1
bbbbbbbb-bbbb-bbbb-bbbb-000000000006 | aaaaaaaa-aaaa-aaaa-aaaa-000000000002 | cccccccc-cccc-cccc-cccc-000000000006 | 2
bbbbbbbb-bbbb-bbbb-bbbb-000000000007 | aaaaaaaa-aaaa-aaaa-aaaa-000000000002 | cccccccc-cccc-cccc-cccc-000000000000 | 3
bbbbbbbb-bbbb-bbbb-bbbb-000000000008 | aaaaaaaa-aaaa-aaaa-aaaa-000000000002 | cccccccc-cccc-cccc-cccc-000000000001 | 4
bbbbbbbb-bbbb-bbbb-bbbb-000000000011 | aaaaaaaa-aaaa-aaaa-aaaa-000000000003 | cccccccc-cccc-cccc-cccc-000000000004 | 1
bbbbbbbb-bbbb-bbbb-bbbb-000000000010 | aaaaaaaa-aaaa-aaaa-aaaa-000000000003 | cccccccc-cccc-cccc-cccc-000000000003 | 2
bbbbbbbb-bbbb-bbbb-bbbb-000000000009 | aaaaaaaa-aaaa-aaaa-aaaa-000000000003 | cccccccc-cccc-cccc-cccc-000000000002 | 3
bbbbbbbb-bbbb-bbbb-bbbb-000000000012 | aaaaaaaa-aaaa-aaaa-aaaa-000000000004 | cccccccc-cccc-cccc-cccc-000000000005 | 1
bbbbbbbb-bbbb-bbbb-bbbb-000000000013 | aaaaaaaa-aaaa-aaaa-aaaa-000000000004 | cccccccc-cccc-cccc-cccc-000000000006 | 2
bbbbbbbb-bbbb-bbbb-bbbb-000000000014 | aaaaaaaa-aaaa-aaaa-aaaa-000000000004 | cccccccc-cccc-cccc-cccc-000000000000 | 3
(18 rows)
We can now obtain only the first C entry associated to a A entry by selecting only entries with rowNumber=1:
select *
from (
select id,id_a,id_c,ROW_NUMBER()
over (partition by id_a order by id_a) as rowNumber from B)
as aggregate
where aggregate.rowNumber=1;
Result:
id | id_a | id_c | rownumber
--------------------------------------+--------------------------------------+--------------------------------------+-----------
bbbbbbbb-bbbb-bbbb-bbbb-000000000000 | aaaaaaaa-aaaa-aaaa-aaaa-000000000000 | cccccccc-cccc-cccc-cccc-000000000000 | 1
bbbbbbbb-bbbb-bbbb-bbbb-000000000004 | aaaaaaaa-aaaa-aaaa-aaaa-000000000001 | cccccccc-cccc-cccc-cccc-000000000004 | 1
bbbbbbbb-bbbb-bbbb-bbbb-000000000017 | aaaaaaaa-aaaa-aaaa-aaaa-000000000002 | cccccccc-cccc-cccc-cccc-000000000003 | 1
bbbbbbbb-bbbb-bbbb-bbbb-000000000011 | aaaaaaaa-aaaa-aaaa-aaaa-000000000003 | cccccccc-cccc-cccc-cccc-000000000004 | 1
bbbbbbbb-bbbb-bbbb-bbbb-000000000012 | aaaaaaaa-aaaa-aaaa-aaaa-000000000004 | cccccccc-cccc-cccc-cccc-000000000005 | 1
(5 rows)
By joining C it is now possible to sort by lastname:
select aggregate.id_a,c.lastname
from (
select id,id_a,id_c,ROW_NUMBER()
over (partition by id_a order by id_a) as rowNumber from B)
as aggregate
join C as c on aggregate.id_c=c.id where aggregate.rowNumber=1
order by c.lastname;
Result:
id_a | lastname
--------------------------------------+----------
aaaaaaaa-aaaa-aaaa-aaaa-000000000004 | C five
aaaaaaaa-aaaa-aaaa-aaaa-000000000003 | C four
aaaaaaaa-aaaa-aaaa-aaaa-000000000001 | C four
aaaaaaaa-aaaa-aaaa-aaaa-000000000002 | C three
aaaaaaaa-aaaa-aaaa-aaaa-000000000000 | C zero
(5 rows)
(Tested with Postgres 14.3)
I am using QueryDSL within a Spring Boot, Spring Data JPA project.
I have the following schema for a table called test:
| id | key | value |
|----|------|-------|
| 1 | test | hello |
| 1 | test | world |
| 2 | test | hello |
| 2 | foo | bar |
| 3 | test | hello |
| 3 | test | world |
Now I want to write the following SQL in QueryDSL:
select id from test where key = 'test' and value = 'hello'
INTERSECT
select id from test where key = 'test' and value = 'world'
Which would give me all ids where key is 'test' and values are 'hello' and 'world'.
I did not find any way of declaring this kind of SQL in QueryDSL yet. I am able to write the two select statements but then I am stuck at combining them with an INTERSECT.
JPAQueryFactory queryFactory = new JPAQueryFactory(em); // em is an EntityManager
QTestEntity qTestEntity = QTestEntity.testEntity;
var q1 = queryFactory.query().from(qTestEntity).select(qTestEntity.id).where(qTestEntity.key("test").and(qTestEntity.value.eq("hello")));
var q2 = queryFactory.query().from(qTestEntity).select(qTestEntity.id).where(qTestEntity.key("test").and(qTestEntity.value.eq("world")));;
In the end I want to retrieve a list of ids which match the given query. In general the amount of intersects can be something around 20 or 30, depending on the number of key/value-pairs I want to search for.
Does anyone know a way how to do something like this with QueryDSL ?
EDIT:
Assume the following schema now, with two tables: test and 'user':
test:
| userId | key | value |
|---------|------|-------|
| 1 | test | hello |
| 1 | test | world |
| 2 | test | hello |
| 2 | foo | bar |
| 3 | test | hello |
| 3 | test | world |
user:
| id | name |
|----|----------|
| 1 | John |
| 2 | Anna |
| 3 | Felicita |
The correspond java classes look like this. TestEntity has a composite key consisting of all of its properties.
#Entity
public class TestEntity {
#Id
#Column(name = "userId", nullable = false)
private String pubmedId;
#Id
#Column(name = "value", nullable = false)
private String value;
#Id
#Column(name = "key", nullable = false)
private String key;
}
#Entity
class User {
#Id
private int id;
private String name;
#ElementCollection
private Set<TestEntity> keyValues;
}
How can I map the test table to the keyValues properties within the User class?
Your TestEntity is not really an Entity, since it's id is not a primary key, it's the foreign key to the user table.
If it's only identifiable by using all its properties, it's an #Embeddable, and doesn't have any #Id properties.
You can map a collection of Embeddables as an #ElementCollection part of another entity which has the id as primary key. The id column in your case is not a property of the Embeddable, it's just the foreign key to the main table, so you map it as a #JoinColumn:
#Embeddable
public class TestEmbeddable {
#Column(name = "value", nullable = false)
private String value;
#Column(name = "key", nullable = false)
private String key;
}
#Entity
class User {
#Id
private int id;
#ElementCollection
#CollectionTable(
name="test",
joinColumns=#JoinColumn(name="id")
)
private Set<TestEmbeddable> keyValues;
}
In this case, the QueryDSL becomes something like this (don't know the exact api):
user.keyValues.any().in(new TestEmbeddable("test", "hello"))
.and(user.keyValues.keyValues.any().in(new TestEmbeddable("test", "world"))
In this case I'd probably just use an OR expression:
queryFactory
.query()
.from(qTestEntity) .select(qTestEntity.id)
.where(qTestEntity.key("test").and(
qTestEntity.value.eq("hello")
.or(qTestEntity.value.eq("world")));
However, you specifically mention wanting to use a set operation. I by the way think you want to perform an UNION operation instead of an INSERSECT operation, because the latter one would be empty with the example given.
JPA doesn't support set operations such as defined in ANSI SQL. However, Blaze-Persistence is an extension that integrates with most JPA implementations and does extend JPQL with set operations. I have recently written a QueryDSL extension for Blaze-Persistence. Using that extension, you can do:
List<Document> documents = new BlazeJPAQuery<Document>(entityManager, cbf)
.union(
select(document).from(document).where(document.id.eq(41L)),
select(document).from(document).where(document.id.eq(42L))
).fetch();
For more information about the integration and how to set it up, the documentation is available at https://persistence.blazebit.com/documentation/1.5/core/manual/en_US/index.html#querydsl-integration
We have Hibernate based application where due to a large data set, two sets of tables are created where user_id will either be mapped in the UserTickets table or RestOfWorldTickets table.
Would like to know how #Table on the entity java objects can be dynamically mapped based on some user selection.
#Entity
#Table(name = "**UserTickets**")
public class UserTickets {
#Id
#Column("Internal_id")
#GeneratedValue(strategy = IDENTITY)
private int internalId;
#Column("user_id")
private int userId;
#Column("state")
private String state;
#Column("city")
private String city;
#Column("address")
private String address;
#Column("ticketNumber")
private String ticketNumber;
..
// Setters and Getters
}
UserTickets DB Table
Internal_id | User_id | State | City | Address | ticket_number | ...
101 | 1025 | AZ | Tuscan | .. | 10256912 |
102 | 1026 | NC | Durham | .. | 10256983
RestOfWorldTickets DB Table
Internal_id | User_id | State | City | Address | ticket_number |..
101 | 1058 | {null} | London | .. | 102578963 |..
102 | 1059 | {null} | Berlin | .. | 112763458 |..
The user and table mapping are now defined in a new table.
TableMapping Database table.
Internal_id | User_id | TableMapped |
1 | 1025 | UserTickets |
2 | 1026 | UserTickets |
3 | 1058 | RestOfWorldTickets |
4 | 1059 | RestOfWorldTickets |
So, using the UserTickets result set, how I map #Table attribute on the UserTickets Java object dynamically so that my Criteria API queries will work automatically without changing them to HQL queries?
Maybe using Interceptors http://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/Interceptor.html?
I am quite unsure what you actually need but i try to give my solution based on a few quesses. Changing #Table dynamically is not -afaik- possible but if i guessed right you could have some benefit of inheritance in this case:
1st modify UserTickets to allow inheritance
#Entity
//#Table(name = "**UserTickets**")
#Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class UserTickets {
#Id // this annotation was missing from yours ?
#Column(name="Internal_id")
#GeneratedValue(strategy = GenerationType.SEQUENCE)
// identity generated problems in openjpa so i changed it to SEQUENCE
private int internalId;
#Column(name="user_id") private int userId;
#Column(name="state") private String state;
#Column(name="city") private String city;
#Column(name="address") private String address;
#Column(name="ticketNumber") private String ticketNumber;
}
2nd create a new entity
#Entity
public class RestOfWorldTickets extends UserTickets {
// yes i am just an empty class, TABLE_PER_CLASS gives me the fields
}
This allows you to use criteriaqueries against UserTickets but in addition the queries are done against RestOfWorldTickets also. So now when you search with user id result set will contain results from both tables. Checking/ loggin -for example with instanceof operator- you can see which one the ticket is.
"Disclaimer" i am using and testing with openjpa so there can be some differences/probkems with this solution...
I have a weird (to me anyway) issue with Hibernate which I can't make any sense of.
The code below is my attempt at modeling a ManyToOne relation with an attribute between the entities Case and Suggestion using an additional entity CaseToSuggestion with Case being my aggregate root:
#Entity
#Table(name = "sga_cases")
public class Case {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
// Business key
#Column(name = "caseid", unique = true, nullable = false)
private String caseId;
...
#OneToMany(mappedBy = "associatedCase", orphanRemoval = true, cascade = CascadeType.ALL)
private Set<CaseToSuggestion> associatedSuggestions = new HashSet<CaseToSuggestion>();
...
}
#Entity
#Table(name = "sga_suggestions")
public class Suggestion {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name = "suggestionid", unique = true, nullable = false)
private String suggestionId;
#Column(name = "localizationkey", nullable = false)
private String localizationKey;
#OneToMany(mappedBy = "associatedSuggestion", orphanRemoval = true, cascade = CascadeType.ALL)
private Set<CaseToSuggestion> caseMapping = new HashSet<CaseToSuggestion>();
...
}
#Entity
#Table(name = "sga_case2suggestion")
public class CaseToSuggestion {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name = "feedback")
private float feedback;
#ManyToOne
#JoinColumn(name = "caseid")
private Case associatedCase;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "suggestionid")
private Suggestion associatedSuggestion;
...
}
If I create new objects for the above entities, set the appropriate associations and then store them with the EntityManager everything works fine:
Case c = new Case(...)
Suggestion sugg = new Suggestion(...);
CaseToSuggestion case2sugg = new CaseToSuggestion(c, sugg, 1.0f);
c.getAssociatedSuggestions().add(case2sugg);
sugg.getAssociatedCases().add(case2sugg);
Followed by entityManager.persist(c);
If I want to add a new association to a Case that is already in the database I retrieve the Case and Suggestion entities I want to associate from the EntityManager and add them to a new CaseToSuggestion:
CaseToSuggestion c2s = new CaseToSuggestion(c, s, fb);
c.getAssociatedSuggestions().add(c2s);
s.getAssociatedCases().add(c2s);
Followed by entityManager.merge(c);
The the CaseToSuggestion entity is stored in the database but for every entry I get a "ghost entry" with a new generated id and all fields null:
+----+----------+--------+--------------+
| id | feedback | caseid | suggestionid |
+----+----------+--------+--------------+
| 3 | 1 | 3 | 1 |
| 4 | 1 | 4 | 2 |
| 5 | 1 | 5 | 2 |
| 6 | 0 | NULL | NULL |
| 7 | 1 | 6 | 2 |
| 8 | 0 | NULL | NULL |
| 9 | 1 | 7 | 2 |
| 10 | 0 | NULL | NULL |
+----+----------+--------+--------------+
Does anybody have an idea what might cause this?
OK, I got it.
Removing the OneToMany-Mapping in Suggestion altogether solved the problem for me.
I have problem writing HQL to display distinct applicationId with the latest application (newest createDate) for the following data in the table.
+---------------+-------------+----------+---------------------+
| applicationId | firstName | lastName | createDate |
+---------------+-------------+----------+---------------------+
| 1 | Mark | Johnson | 2010-05-03 00:00:00 |
| 3 | Henry | Jordan | 2010-05-03 00:00:00 |
| 5 | Cindy Spahn | Wilson | 2010-05-03 00:00:00 |
| 5 | Cindy Spahn | Wilson | 2010-05-04 00:00:00 |
| 5 | Cindy Spahn | Wilson | 2010-05-05 00:00:00 |
+---------------+-------------+----------+---------------------+
5 rows in set (0.00 sec)
Below is the result that I'm looking for:
+---------------+-------------+----------+---------------------+
| applicationId | firstName | lastName | createDate |
+---------------+-------------+----------+---------------------+
| 1 | Mark | Johnson | 2010-05-03 00:00:00 |
| 3 | Henry | Jordan | 2010-05-03 00:00:00 |
| 5 | Cindy Spahn | Wilson | 2010-05-05 00:00:00 |
+---------------+-------------+----------+---------------------+
3 rows in set (0.00 sec)
Entities are as follow:
#Entity
#Table(name = "application")
public class Application {
private long applicationId;
private String firstName;
private String lastName;
private List<ApplicationHistory> applicationHistoryList;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public long getApplicationId() {
return applicationId;
}
#OneToMany(mappedBy = "application", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
public List<ApplicationHistory> getApplicationHistoryList() {
return applicationHistoryList;
}
// getter() and setter()
}
and:
#Entity
#Table(name = "applicationHistory")
public class ApplicationHistory {
private Application application;
private final Timestamp createDate = new Timestamp(System.currentTimeMillis());
#ManyToOne
#JoinColumn(name = "applicationId", insertable = false, updatable = false)
public Application getApplication() {
return application;
}
#Id
#Column(columnDefinition = "timestamp default current_timestamp")
public Timestamp getCreateDate() {
return createDate;
}
}
You can use below query:
select a, h.createDate from Application as a join a.applicationHistoryList as h where (a.applicationId, h.createDate) in( SELECT application.applicationId, max(createDate) FROM ApplicationHistory group by application.applicationId)
eg:
Query q = em.createQuery("select a, h.createDate from Application as a join a.applicationHistoryList as h where (a.applicationId, h.createDate) in( SELECT application.applicationId, max(createDate) FROM ApplicationHistory group by application.applicationId) ");
List list = q.getResultList();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Object obj[] = (Object[])iterator.next();
Application a = (Application) obj[0];
System.out.println("ApplicationId="+a.getApplicationId() );
System.out.println("CreateDate="+obj[1] );
}
Try to do it with group by clause:
select ah from ApplicationHistory ah group by ah.applicationId order by ah.createDate desc