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

  • SEARCH
  • Home
  • 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 8280533
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T09:42:45+00:00 2026-06-08T09:42:45+00:00

I am trying to improve performance on an application using Hibernate which is executing

  • 0

I am trying to improve performance on an application using Hibernate which is executing too many SQL calls to the database. I think data fetching can be grouped together to reduce the calls and improve performance but I’m at a bit of a loss here. I’ve looked at the Hibernate documentation about subselects and batch fetching which does help but I don’t think it completely eliminates the problem.

In the example below I need to get details for a list of soldiers that are part of a troop and display it on a webpage.

@Entity
public class Troop {
    @OneToMany(mappedBy="troop")
    public List<Soldier> getSoldiers() {
   ...
}

It’s easy to set the fetch strategy to subselect, batch or eager to retrieve all the soldiers part of this troop without too many SQL statements.

@Entity
public class Soldier {
    @Id
    String soldierId

    String firstName;
    String lastName;

    @OneToMany(mappedBy="address")
    public List<Soldier> getAddress() {
     ...
    @OneToMany(mappedBy="combatHistory")
    public List<Soldier> getCombatHistory() {
      ...
    @OneToMany(mappedBy="medicalHistory")
    public List<Soldier> getMedicalHistory() {
      ...
}

Each soldier entity has multiple one to many relationships with other entities that are lazily loaded. I need to initialize these collections and retrieve values from them. If a Soldier has 3 one to many relationships and a Troop has 1,000 soldiers that would result in 3 x 1,000 SQL calls!

Is there a way to optimize this by reducing the number of calls? Since I already know the soldierIds I need to retrieve can I retrieve the entities and have them available in the first level cache?

For example I could query

from Address as a where a.soldierId in (...)
from CombatHistory as a where a.soldierId in (...)
from MedicalHistory as a where a.soldierId in (...)

If the Address, CombatHistory etc entities can be cached then a SQL select won’t be executed when the collection is accessed within each soldier. This would reduce the number of calls to one per collection (3 in this case) rather than one per collection per soldier (3 x 1000)

I didn’t really see much in the documentation about addressing this issue so any hints and ideas are greatly appreciated. Keep in mind that since these collections are Lists and not Sets the left join fetch cannot be executed on multiple collections or Hibernate will return an exception.

HibernateException: cannot simultaneously fetch multiple bags 
  • 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-08T09:42:46+00:00Added an answer on June 8, 2026 at 9:42 am

    You could also use the annotation @Fetch(FetchMode.SUBSELECT) on your collection
    if you “touch” one collection of that type, all collections will be fetched in ONE single SQL request.

    @Entity
    public class Country implements java.io.Serializable {
    
        private long id;
        private int version;
        private String country;
        private Set<City> cities = new HashSet<City>(0);
    
        @Fetch(FetchMode.SUBSELECT)
        @OneToMany(mappedBy = "country", cascade = CascadeType.ALL)
        public Set<City> getCities() {
            return cities;
        }
    
    
        ...
    }
    

    Here is an example of how to use it:

        public List<Country> selectCountrySubSelect() {
            List<Country> list = getSession().createQuery("select c from Country c").list();
            // You don't have to initialize every collections
            // for (Country country : list) {
            // Hibernate.initialize(country.getCities());
            // }
            // but just "touch" one, and all will be initialized
            Hibernate.initialize(((Country) list.get(0)).getCities());
            return list;
        }
    

    the logs :

    DEBUG org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections():  - 2 collections were found in result set for role: business.hb.Country.cities
    DEBUG org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection():  - Collection fully initialized: [business.hb.Country.cities#1]
    DEBUG org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection():  - Collection fully initialized: [business.hb.Country.cities#2]
    DEBUG org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections():  - 2 collections initialized for role: business.hb.Country.cities
    DEBUG org.hibernate.engine.internal.StatefulPersistenceContext.initializeNonLazyCollections():  - Initializing non-lazy collections
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to improve performance by limiting my objects in memory by using
I am trying to improve the performance of my web-application so I decided to
I'm trying to improve performance of an existing MySQL database. It's a database regarding
I am developing an application using asp.net 2.0 (C#), in which I am trying
I'm trying to improve performance for my application, and I'd like to change from
I am trying to improve the performance of a web application. I have metrics
I am trying to improve the performance of the threaded application with real-time deadlines.
I'm trying to improve performance for an application that does a lot of bit
I am trying to improve the performance of a Silverlight 4 WCF RIA application.
I'm trying to improve performance in our app. I've got performance information in the

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.