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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T06:37:37+00:00 2026-05-26T06:37:37+00:00

I have a base method that I’m writing in order to not repeat the

  • 0

I have a base method that I’m writing in order to not repeat the same hibernate session/transaction logic over and over. It’s fairly simple, but there’s a specific issue that I’m not sure can be solved with this approach.

Imagine that you have a User entity and a Permission entity. If a request is made to save a user along with its matching permissions, then I think that it would make sense to perform both operations in a single transaction, since being able to save only one of those entities could be considered data corruption. For example, failing to save the user’s permissions would warrant a rollback on previously inserted user data.

I made the following method to allow generic hibernate operations that could work with the current transaction if it were necessary, although I now think that in its current form it won’t work since calling session.beginTransaction(); will probably return a new transaction even if the previous hasn’t been commited (is this the case?). Suppose that I changed it in order to have it return the current session and transaction if it was specified that there would be more operations for the current transaction, do you think it would work? Would it be advisable to do something like this, or would you recommend a change of approach? Thanks

protected <T> void baseOperation(Class<T> entityClass, List<T> instances, BaseHibernateDAO.Operations operation, boolean isLastOperation) throws Exception
{
    Session session = null;
    Transaction transaction = null;
    boolean caughtException = false;

    //get session from factory
    session = HibernateSessionFactory.getSession();

    try
    {
        //get current transaction
        transaction = session.beginTransaction();

        for (Object instance : instances) //perform operation on all instances
        {
            log.debug(String.format("Will perform %s operation on %s instance.", operation.name(), entityClass.getName()));

            switch (operation) //perform requested operation
            {
                case SAVE:
                    session.save(instance);
                    break;
                case UPDATE:
                    session.update(instance);
                    break;
                case SAVEORUPDATE:
                    session.saveOrUpdate(instance);
                    break;
                case DELETE:
                    session.saveOrUpdate(instance);
                    break;
            }

            log.debug(String.format("%s operation on %s instance was succesful.", operation.name(), entityClass.getName()));
        }

        session.flush(); //synchronize

        if (isLastOperation) //if this is the last operation of the transaction
        {
            transaction.commit();
            log.debug("Transaction commited succesfully.");
        }
    }
    catch (Exception e) //error occurred
    {
        caughtException = true;

        //roll-back if transaction exists
        if (transaction != null)
        {
            transaction.rollback();
        }

        //log and re-throw
        log.error("An error occurred during transaction operation.", e);
        throw e;
    }
    finally //cleanup tasks
    {
        if (isLastOperation || caughtException) //close session if there are no more pending operations or if an error occurred
        {
            HibernateSessionFactory.closeSession();
        }
    }
}
  • 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-26T06:37:37+00:00Added an answer on May 26, 2026 at 6:37 am

    “Advisable” would be to stop trying to rewrite code that’s already been written, debugged, dragged through the mud, debugged more, and deployed thousands of times. I.e, the issues and considerations you’re encountering have been encountered and overcome before, and the solutions are proven. Further, having been extensively used and improved, they require much less effort to use than what you’re putting into your custom solution. Check out Spring’s Hibernate support, especially “Implementing DAOs based on plain Hibernate 3 API” and “Declarative transaction demarcation“. For further reading, there’s a whole chapter on transaction management.

    I have a sample project on github where you can see a very simple example of using Spring to manage Hibernate Sessions and transactions in the context of a webapp (using Spring MVC).

    Update: For those who come along later, so they don’t have to dig through the comments:

    There are three general ways to use Spring’s transaction handling: declaratively defining which methods are transactional with XML, declaratively annotating methods as @Transactional, or programmatically using TransactionTemplate.

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

Sidebar

Related Questions

I have a base class with a virtual method, and multiple subclasses that override
I have a recursive method on the base form that takes in a control
In class: \\\android 1.5 source\frameworks\base\services\java\com\android\server\HardwareService I have found method that looks like would help
Here's the situation. I have a base class which implements a method that accepts
I have a derived class with a method that overrides the base class's method,
I have a webservice with a method that takes a parameter of abstract base
In the code base I'm working in there have a method that has the
I have a base class that has a method that creates an instance of
I have a base class that has a method that gets executed by derived
I have a base form class that contains a method that returns a DataTable:

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.