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 825441
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T03:15:21+00:00 2026-05-15T03:15:21+00:00

I am having trouble optimizing Hibernate queries to avoid performing joins or secondary selects.

  • 0

I am having trouble optimizing Hibernate queries to avoid performing joins or secondary selects.

When a Hibernate query is performed (criteria or hql), such as the following:

return getSession().createQuery(("from GiftCard as card where card.recipientNotificationRequested=1").list();

… and the where clause examines properties that do not require any joins with other tables… but Hibernate still performs a full join with other tables (or secondary selects depending on how I set the fetchMode).

The object in question (GiftCard) has a couple ManyToOne associations that I would prefer to be lazily loaded in this case (but not necessarily all cases). I want a solution that I can control what is lazily loaded when I perform the query.

Here’s what the GiftCard Entity looks like:

@Entity
@Table(name = "giftCards")
public class GiftCard implements Serializable
{
 private static final long serialVersionUID = 1L;

 private String id_;
 private User buyer_;
 private boolean isRecipientNotificationRequested_;


 @Id
 public String getId()
 {
  return this.id_;
 }

 public void setId(String id)
 {
  this.id_ = id;
 }

 @ManyToOne
 @JoinColumn(name = "buyerUserId")
 @NotFound(action = NotFoundAction.IGNORE)
 public User getBuyer()
 {
  return this.buyer_;
 }
 public void setBuyer(User buyer)
 {
  this.buyer_ = buyer;
 }

 @Column(name="isRecipientNotificationRequested", nullable=false, columnDefinition="tinyint")
 public boolean isRecipientNotificationRequested()
 {
  return this.isRecipientNotificationRequested_;
 }

 public void setRecipientNotificationRequested(boolean isRecipientNotificationRequested)
 {
  this.isRecipientNotificationRequested_ = isRecipientNotificationRequested;
 }
}
  • 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-05-15T03:15:22+00:00Added an answer on May 15, 2026 at 3:15 am

    As said

    I want a solution that I can control what is lazily loaded when I perform the query

    If you have a mapping like this one

    @Entity
    public class GiftCard implements Serializable {
    
        private User buyer;
    
        @ManyToOne
        @JoinColumn(name="buyerUserId")
        public User getBuyer() {
            return this.buyer;
        }
    }
    

    Any *ToOne relationship, such as @OneToOne and @ManyToOne, is, by default, FetchType.EAGER which means it will be always fetched. But, it could not be what you want. What you say as I can control what is lazily loaded can be translated as Fetching Strategy. POJO in Action book supports a pattern like this one (Notice method signature)

    public class GiftCardRepositoryImpl implements GiftCardRepository {
    
         public List<GiftCard> findGiftCardWithBuyer() {
             return sessionFactory.getCurrentSession().createQuery("from GiftCard c inner join fetch c.buyer where c.recipientNotificationRequested = 1").list();
         }
    
    }
    

    So based on your use case, you can create your own find…With…And… method. It will take care of fetching just what you want

    But it has a problem: It does not support a generic method signature. For each @Entity repository, you have to define your custom find…With…And method. Because of that, i show you how i define a generic repository

    public interface Repository<INSTANCE_CLASS, UPDATABLE_INSTANCE_CLASS, PRIMARY_KEY_CLASS> {
    
        void add(INSTANCE_CLASS instance);
        void remove(PRIMARY_KEY_CLASS id);
        void update(PRIMARY_KEY_CLASS id, UPDATABLE_INSTANCE_CLASS updatableInstance);
        INSTANCE_CLASS findById(PRIMARY_KEY_CLASS id);
        INSTANCE_CLASS findById(PRIMARY_KEY_CLASS id, FetchingStrategy fetchingStrategy);
        List<INSTANCE_CLASS> findAll();
        List<INSTANCE_CLASS> findAll(FetchingStrategy fetchingStrategy);
        List<INSTANCE_CLASS> findAll(int pageNumber, int pageSize);
        List<INSTANCE_CLASS> findAll(int pageNumber, int pageSize, FetchingStrategy fetchingStrategy);
        List<INSTANCE_CLASS> findAllByCriteria(Criteria criteria);
        List<INSTANCE_CLASS> findAllByCriteria(Criteria criteria, FetchingStrategy fetchingStrategy);
        List<INSTANCE_CLASS> findAllByCriteria(int pageNumber, int pageSize, Criteria criteria);
        List<INSTANCE_CLASS> findAllByCriteria(int pageNumber, int pageSize, Criteria criteria, FetchingStrategy fetchingStrategy);
    
    }
    

    But, sometimes, you do not want all of methods defined by generic Repository interface. Solution: create an AbstractRepository class which will implement a dummy repository. Spring Framework, for instance, heavily use this kind of pattern Interface >> AbstractInterface

    public abstract class AbstractRepository<INSTANCE_CLASS, UPDATABLE_INSTANCE_CLASS, PRIMARY_KEY_CLASS> implements Repository<INSTANCE_CLASS, UPDATABLE_INSTANCE_CLASS, PRIMARY_KEY_CLASS> {
    
        public void add(INSTANCE_CLASS instance) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    
        public void remove(PRIMARY_KEY_CLASS id) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    
        public void update(PRIMARY_KEY_CLASS id, UPDATABLE_INSTANCE_CLASS updatableInstance) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    
        public INSTANCE_CLASS findById(PRIMARY_KEY_CLASS id) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    
        public INSTANCE_CLASS findById(PRIMARY_KEY_CLASS id, FetchingStrategy fetchingStrategy) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    
        public List<INSTANCE_CLASS> findAll() {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    
        public List<INSTANCE_CLASS> findAll(FetchingStrategy fetchingStrategy) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    
        public List<INSTANCE_CLASS> findAll(int pageNumber, int pageSize) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    
        public List<INSTANCE_CLASS> findAll(int pageNumber, int pageSize, FetchingStrategy fetchingStrategy) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    
        public List<INSTANCE_CLASS> findAllByCriteria(Criteria criteria) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    
        public List<INSTANCE_CLASS> findAllByCriteria(Criteria criteria, FetchingStrategy fetchingStrategy) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    
        public List<INSTANCE_CLASS> findAllByCriteria(int pageNumber, int pageSize, Criteria criteria) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    
        public List<INSTANCE_CLASS> findAllByCriteria(int pageNumber, int pageSize, Criteria criteria, FetchingStrategy fetchingStrategy) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    
    }
    

    So your GiftCardRepository can be re-written as (See extends instead of implements) and just overrides what you really want

    public class GiftCardRepository extends AbstractRepository<GiftCard, GiftCard, String> {
    
        public static final GIFT_CARDS_WITH_BUYER GIFT_CARDS_WITH_BUYER = new GIFT_CARDS_WITH_WITH_BUYER();
        public static final GIFT_CARDS_WITHOUT_NO_RELATIONSHIP GIFT_CARDS_WITHOUT_NO_RELATIONSHIP = new GIFT_CARDS_WITHOUT_NO_RELATIONSHIP();
    
        public List<GiftCard> findAll(FetchingStrategy fetchingStrategy) {
            sessionFactory.getCurrentSession().getNamedQuery(fetchingStrategy.toString()).list();
        }
    
    
        /**
          * FetchingStrategy is just a marker interface
          * public interface FetchingStrategy {}
          *
          * And AbstractFetchingStrategy allows you to retrieve the name of the Fetching Strategy you want, by overriding toString method
          * public class AbstractFetchingStrategy implements FetchingStrategy {
          *
          *     @Override
          *     public String toString() {
          *         return getClass().getSimpleName();
          *     } 
          *
          * }
          * 
          * Because there is no need to create an instance outside our repository, we mark it as private
          * Notive each FetchingStrategy must match a named query
          */
        private static class GIFT_CARDS_WITH_BUYER extends AbstractFetchingStrategy {}    
        private static class GIFT_CARDS_WITHOUT_NO_RELATIONSHIP extends AbstractFetchingStrategy {}
    }
    

    Now we externalize our named query in a multiline – and readable and maintainable – xml file

    // app.hbl.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
        <query name="GIFT_CARDS_WITH_BUYER">
            <![CDATA[
                from 
                    GiftCard c
                left join fetch 
                    c.buyer
                where
                    c.recipientNotificationRequested = 1
            ]]>
        </query>
        <query name="GIFT_CARDS_WITHOUT_NO_RELATIONSHIP">
            <![CDATA[
                from 
                    GiftCard
            ]]>
        </query>
    </hibernate-mapping>
    

    So if you want to retrieve you GiftCard with Buyer, just call

    Repository<GiftCard, GiftCard, String> giftCardRepository;
    
    List<GiftCard> giftCardList = giftCardRepository.findAll(GiftCardRepository.GIFT_CARDS_WITH_WITH_BUYER);
    

    And to retrieve our GiftCard without no relationship, just call

    List<GiftCard> giftCardList = giftCardRepository.findAll(GiftCardRepository.GIFT_CARDS_WITHOUT_NO_RELATIONSHIP);
    

    or use import static

    import static packageTo.GiftCardRepository.*;
    

    And

    List<GiftCard> giftCardList = giftCardRepository.findAll(GIFT_CARDS_WITHOUT_NO_RELATIONSHIP);
    

    I hope it can be useful to you!

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

Sidebar

Related Questions

I am having some trouble optimizing a query, and was hoping that someone here
I'm having trouble optimizing this query: SELECT a.id FROM a JOIN b ON a.id=b.id
I am having trouble optimizing a relatively simple query involving a GROUP BY, ORDER
Having trouble with an HQL query. If I remove the avg(..) from it it
I'm having trouble optimizing a C++ program for the fastest runtime possible. The requirements
Having trouble with a query to return the newest order of any grouped set
Having trouble displaying MonthName in a DataGridView from data in MySQL Query: SELECT ItemName,
Having trouble with query results. The getSales() function works great the first time it
Having trouble with each function... Will try to explain by example... In my code,
Having trouble with an .htaccess file on WAMP. Works on the live server, but

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.