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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T07:04:56+00:00 2026-05-18T07:04:56+00:00

i’m using spring + hibernate. All my HibernateDAO use directly sessionFactory. I have application

  • 0

i’m using spring + hibernate. All my HibernateDAO use directly sessionFactory.

I have application layer -> service layer -> DAO layer and all collections is lazly loaded.

So, the problem is that sometime in the application layer(that contains GUI/swing) i load an entity using a service layer method(that contains @Transactional annotation) and i want to use a lazly property of this object, but obviusly the session is already closed.

What is the best way to resolve this trouble?

EDIT

I try to use a MethodInterceptor, my idea is to write an AroundAdvice for all my Entities and use annotation, so for example:

// Custom annotation, say that session is required for this method
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SessionRequired {


// An AroundAdvice to intercept method calls
public class SessionInterceptor implements MethodInterceptor {

    public Object invoke(MethodInvocation mi) throws Throwable {
        bool sessionRequired=mi.getMethod().isAnnotationPresent(SessionRequired.class);
        // Begin and commit session only if @SessionRequired
        if(sessionRequired){
            // begin transaction here
        }
        Object ret=mi.proceed();
        if(sessionRequired){
            // commit transaction here
        }
        return ret;
    }
}

// An example of entity
@Entity
public class Customer implements Serializable {

    @Id
    Long id;

    @OneToMany
    List<Order> orders;  // this is a lazy collection

    @SessionRequired
    public List<Order> getOrders(){
        return orders;
    }
}

// And finally in application layer...
public void foo(){
    // Load customer by id, getCustomer is annotated with @Transactional
    // this is a lazy load
    Customer customer=customerService.getCustomer(1); 

    // Get orders, my interceptor open and close the session for me... i hope...
    List<Order> orders=customer.getOrders();

    // Finally use the orders
}

Do you think can this work?
The problem is, how to register this interceptor for all my entities without do it in xml file?
There is a way to do it with annotation?

  • 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-18T07:04:57+00:00Added an answer on May 18, 2026 at 7:04 am

    Hibernate recently introduced fetch profiles which (in addition to performance tuning) is ideal for solving issues like this. It allows you to (at runtime) choose between different loading and initialization strategies.

    http://docs.jboss.org/hibernate/core/3.5/reference/en/html/performance.html#performance-fetching-profiles

    Edit (added section on how to set the fetch profile using an interceptor):

    Before you get started: Check that fetch profiles actually will work for you. I haven’t used them myself and see that they are currently limited to join fetches. Before you waste time on implementing and wiring up the interceptor, try setting the fetch profile manually and see that it actually solves your problem.

    There are many ways to setup interceptors in Spring (according to preference), but the most straight-forward way would be to implement a MethodInterceptor (see http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop-api.html#aop-api-advice-around). Let it have a setter for the fetch profile you want and setter for the Hibernate Session factory:

    public class FetchProfileInterceptor implements MethodInterceptor {
    
        private SessionFactory sessionFactory;
        private String fetchProfile;
    
        ... setters ...    
    
        public Object invoke(MethodInvocation invocation) throws Throwable {
            Session s = sessionFactory.openSession(); // The transaction interceptor has already opened the session, so this returns it.
            s.enableFetchProfile(fetchProfile);
            try {
                return invocation.proceed();
            } finally {
                s.disableFetchProfile(fetchProfile);
            }
        }
    }
    

    Lastly, enable the interceptor in the Spring config. This can be done in several ways and you probably already have a AOP setup that you can add it to. See http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-schema.

    If you’re new to AOP, I’d suggest trying the “old” ProxyFactory way first (http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop-api.html#aop-api-proxying-intf) because it’s easier to understand how it works. Here’s some sample XML to get you started:

    <bean id="fetchProfileInterceptor" class="x.y.zFetchProfileInterceptor">
      <property name="sessionFactory" ref="sessionFactory"/>
      <property name="fetchProfile" ref="gui-profile"/>
    </bean>
    
    <bean id="businessService" class="x.y.x.BusinessServiceImpl">
      <property name="dao" .../>
      ...
    </bean>
    
    <bean id="serviceForSwinGUI" 
        class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="proxyInterfaces" value="x.y.z.BusinessServiceInterface/>
    
        <property name="target" ref="businessService"/>
        <property name="interceptorNames">
            <list>
                <value>existingTransactionInterceptorBeanName</value>
                <value>fetchProfileInterceptor</value>
            </list>
        </property>
    </bean>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
In order to apply a triggered animation to all ToolTip s in my app,
I want use html5's new tag to play a wav file (currently only supported
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I want to count how many characters a certain string has in PHP, but
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
Is it possible to replace javascript w/ HTML if JavaScript is not enabled on
Seemingly simple, but I cannot find anything relevant on the web. What is 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.