简体   繁体   中英

How to retrieve all Entities Grouped By Id?

I am using spring-jpa and using entity manager for persistence.

I am developing a spring-application and trying to retrieve all the entities that have persisted before a certain time grouping them on their Id.

Tried the following query inside a createQuery using entitymanager

"Select se From SampleEntity se where se.createdDate > :elapsedTime group by se.uid"

The model looks like this:

class SampleEntity
{

@Id
private String uid;      //Cannot be null

@Id
private String uid2;     //Should be unique, 

//also combo of uid, uid2 should be unique

private String name;

private Date createdDate;

private Date updatedDate;

}

Assume the following data in db

Uid     Uid2     Name     CreatedDate            UpdatedDate
A-123   X-123     AX      10/6/2019 10:00:00AM   10/6/2019 10:00:00AM
A-123   X-124     AX      10/6/2019 10:00:20AM   10/6/2019 10:00:20AM
B-124   Y-125     BY      10/6/2019 10:01:00AM   10/6/2019 10:01:00AM
B-124   Y-126     BY      10/6/2019 10:01:20AM   10/6/2019 10:01:20AM

Actual result:

Keep getting error "not a group by expression"

Expected:

I want the entity to be retrived as groups of Uid.

So, I want to be able to query and retrieve a list of 2 objects where each object in turn would be a list/array of entities that have the same uid.

Object 1 - would contain 2 sample entity objects that would contain data from the following 2 rows: A-123 X-123 AX 10/6/2019 10:00:00AM 10/6/2019 10:00:00AM A-123 X-124 AX 10/6/2019 10:00:20AM 10/6/2019 10:00:20AM

Object 2 - would contain 2 sample entity objects that would contain data from the following 2 rows: B-124 Y-125 BY 10/6/2019 10:01:00AM 10/6/2019 10:01:00AM B-124 Y-126 BY 10/6/2019 10:01:20AM 10/6/2019 10:01:20AM

Is this possible? If yes, how? What am I missing?

When using GROUP BY only the grouping columns or aggregates function (COUNT...) can be used in the SELECT clause, just as with SQL queries. This example would be a correct query, it would result in a list of uid.

Select se.uid From SampleEntity se where se.createdDate > :elapsedTime group by se.uid

However, his query will not allow you to retrieve a list of list of objects, as SQL group by does not work this way, and I don't think this is feasible with JPA. You would have to do a regular query and build the your nested lists in the service layer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM