Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8971685
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T18:01:10+00:00 2026-06-15T18:01:10+00:00

I have two entities: ResourceFile: @Entity @Table(name = resource_file) public class ResourceFile extends IdEntity<Integer>

  • 0

I have two entities:

ResourceFile:

@Entity
@Table(name = "resource_file")
public class ResourceFile extends IdEntity<Integer> {

    @Id
    @SequenceGenerator(name = "resource_file_id_generator", sequenceName = "resource_file_id", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "resource_file_id_generator")
    @Column(name = "id", unique = true, nullable = false)
    @Nonnegative
    private Integer id;

    ...
}

FavoriteResourceFile:

@Entity
@Table(name = "favorite_resource_file")
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class FavoriteResourceFile extends IdEntity<FavoriteResourceFileId> {

    @EmbeddedId
    private FavoriteResourceFileId id;

    @MapsId("resourceFileId")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "resource_file_id", nullable = false)
    private ResourceFile resourceFile;

    ...

}

And I want to make the following query “select all resource files and sort them by favourite resource file’s count”.

In SQL it looks like:

select rf.id, count(frf.resource_file_id) from resource_file rf
left join favorite_resource_file frf on frf.resource_file_id = rf.id
group by rf.id
order by count(rf.id) desc;

But I can’t understand how to do it with Spring Data and how to make mapping to ResourceFile entity at the end.

Some limitations:

  • I can’t make relation to FavoriteResourceFile in ResourceFile,
    because they are located in different modules
  • I don’t want to use native SQL or JPA query (as strings).
  • It’ll be preferable to use Meta-models, Specification or QueryDSL, because they are already used in project.

Can someone help me?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T18:01:12+00:00Added an answer on June 15, 2026 at 6:01 pm

    You can use your custom repository implementation along with Crud/PagingAndSorting repository implementation, like this:

    End-point repo:

    public interface ResourceFileRepository extends
        PagingAndSortingRepository<ResourceFile, Integer>,
        ResourceFileRepositoryCustom {
    }
    

    Custom repo:

    public interface ResourceFileRepositoryCustom {
        List<ResourceFile> getResourceFilesOrderByFavourites();
    }
    

    Custom repo implementation with actual code to retrive ResourceFile’s ordered by favourite count (notice it is ResourceFileRepositoryImpl and not ResourceFileRepositoryCustomImpl).

    I didn’t have those embeded keys, so I had to simplify it a little bit.
    The query is going FROM the FavoriteResourceFile, because ResourceFile don’t have own relation to FavoriteResourceFile.

    public class ResourceFileRepositoryImpl implements ResourceFileRepositoryCustom {
        @PersistenceContext
        private EntityManager em;
    
        public void setEntityManager(EntityManager em) {
            this.em = em;
        }
    
        @Override
        public List<ResourceFile> getResourceFilesOrderByFavourites() {
            CriteriaBuilder criteriaBuilder = this.em.getCriteriaBuilder();
            CriteriaQuery<ResourceFile> q = criteriaBuilder
                    .createQuery(ResourceFile.class);
            Root<FavoriteResourceFile> root = q.from(FavoriteResourceFile.class);
            Join<FavoriteResourceFile, ResourceFile> join = root.join(
                     FavoriteResourceFile_.resourceFile, JoinType.LEFT);
            q.select(join);
            q.groupBy(join.get(ResourceFile_.id));
            q.orderBy(criteriaBuilder.desc(
                          criteriaBuilder.count(
                              join.get(ResourceFile_.id))));
    
            TypedQuery<ResourceFile> query = this.em.createQuery(q);
            return query.getResultList();
        }
    }
    

    To see full example project (with some very basic sql and test) – checkout/fork/etc:
    https://github.com/rchukh/StackOverflowTests/tree/master/13669324

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have two entities: Event and Comment. @Entity @Table(name = events) public class Event
I have two entities Room.php /** * @ORM\Table(name=room) * @ORM\Entity(repositoryClass=Ahsio\StackBundle\Repository\RoomRepository) */ class Room {
I have two entities A and B. public class A{ @Id @GeneratedValue private Integer
A have two entities. For example timing settings and orders. @Entity public class TimingSettings{
I have two entities like the following: @Entity public class Trip { @OneToMany(mappedBy =
I have two entities @Entity public class Tabulka{ @OneToMany(mappedBy = tabulka) private List<VysledkyHraca> vysledkyHraca;
I have two entities: @Entity public class File ....... @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id;
I have two entities. Sports: @Entity public class Sports implements Serializable { private static
I have two entities User and Group: @Entity public class User implements Serializable {
I have two entities: Recipe and Ingredient. Entites: public class Ingredient { public int

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.