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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T10:36:49+00:00 2026-05-15T10:36:49+00:00

I have some questions about interaction with Hibernate: Do I use openSession or getCurrentSession

  • 0

I have some questions about interaction with Hibernate:

  1. Do I use openSession or getCurrentSession (without jta, thread instead)?
  2. How do I mix session operations with the Swing GUI? Is good have something like the following code in a JavaBean class?

    public void actionPerformed(ActionEvent event) {
        // session code
    }
    
  3. Can I add methods to my entities that contains HQL queries or is this a bad practice? For example:

     // This method is in an entity MyOtherEntity.java class
     public int getDuration(){
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        int sum = (Integer) session.createQuery("select sum(e.duration) as duration from MyEntity as e where e.myOtherEntity.id=:id group by e.name").
            .setLong("id", getId());
            .uniqueResult();
        return sum;
     }
    

How can I do this in a better and elegant way?

UPDATE
A widely used practice is to make a service/dao class to achieve CRUD operation of our entities class. But why is this good?
Why do I have to write a class for each my entities to manage it? Where is the real advantage?

UPDATE 2
Service class is a DAO pattern? What does this mean?
Arthur Ronald F D Garcia’s repository example is a DAO pattern, is this what is called a “service layer”?

  • 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-15T10:36:50+00:00Added an answer on May 15, 2026 at 10:36 am

    If you want to rely on plain Hibernate API you can use a Service layer because

    • It is Use case driven
    • Delimit Transaction boundaries

    So you can create a AccountService, for instance, like

    public static path.to.HibernateUtil.getSessionFactory;
    
    public class AccountService {
    
        public void withdraw(Integer accountNumber, BigDecimal amount) throws Exception {
            /**
              * Here you set up Transaction boundaries
              */
            getSessionFactory().getCurrentSession().beginTransaction();
    
            // Some actions goes here
    
            getSessionFactory().getCurrentSession().getTransaction().commit();
        }
    
    }
    

    You usually need a repository when performing some action inside your Service layer. You can Think of repository as a data provider and storage. Here you can see how i implement my repository.

    If you want a maintainable and readable HQL query, I advice you externalize your HQL queries in a multline and externalized xml file

    <?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 inside your Swing GUI Event, you can call your service layer like

    public void actionPerformed(ActionEvent event) {
        // Some related Swing GUI actions goes here (retrieve User input, validate data and so on...)
    
        accountService.withdraw(accountNumber, new BigDecimal(amount));
    }
    

    And it is not a good idea To use persistence actions inside your Entity. If you need to perform persistence related issues inside your Entity, I Think it is better you pass your repository as parameter to your Entity

    public class Account {
    
       public void doSomething(AccountRepository repository) {
           // code goes here
       }
    
    }
    

    Maybe you want to see this Thread

    I advice you Take a look at Java Persistence with Hibernate book, chapter 9 (Working with objects). ATT: read carefully

    UPDATE

    Why is good have a service layer ?

    First of all

    • It is Use case driven (It draws what your app should do)

    Second of all

    • It delimit Transaction boundaries

    Suppose here goes your Service layer

    public class MyService {
    
        public void doSomething() {
            getSessionFactory().beginTransaction();
    
            // A POJO doing some operation
    
            // Other POJO doing other operation
    
            // Another POJO doing another operation
    
            getSessionFactory().getTransaction().commit();
        }
    
    }
    

    Notice you just define one Transaction boundary instead of defining each one inside each POJO. And more, what happens whether your business rule inside your Swing GUI need to be used inside other component. Will you use a Ctrl-c + Ctrl-v ???

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

Sidebar

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.