1

I write my project on Servlet and Hibernate. This is example of my source code:

@Override
    public Long insertUser(User user) throws HibernateException {
        Long id;
        try{
            session = sessionFactory.openSession();
            session.beginTransaction();
            id = (Long) session.save(user);
            session.getTransaction().commit();
        }finally{
            if(session != null && session.isOpen())
                session.close();
        }

        return id;
    }

I have a question, i often write the same code:

session = sessionFactory.openSession();
session.beginTransaction();

session.getTransaction().commit();

if(session != null && session.isOpen())
session.close();

I think that this is very strange. Do you know solution for simplify code?

  • As far as my experience goes you have to write either at minimum Session s = this.session.getCurrentSession();. For that you need to autowire session via your spring config file. Also you need to do the same for your transactionmanager. I have the full code at my home laptop, will post the code later today. – user3509208 Feb 22 '16 at 19:32
  • If you're using a real Java EE server, just use EJB. If you're using a barebones servletcontainer like Tomcat, use Spring or consider migrating to TomEE so you can use EJB (and JPA instead of legacy Hibernate). Is this Q&A helpful? http://stackoverflow.com/q/18369356 – BalusC Feb 22 '16 at 20:11
  • @BalusC Using EJB to simplify a small part of code is over engineering in my opinion. EJB is for managers to tell stories to customers about business logic (I really hate this term). – v.ladynev Feb 23 '16 at 06:18
  • user3509208, thank you :) i am waiting. But if i use Session s = this.session.getCurrentSession(); I anyway must write session.beginTransaction(); and session.getTransaction().commit();, right? – GermanSevostyanov Feb 23 '16 at 07:06
  • @v.ladynev: still hanging in J2EE era? It's since Java EE 5 just matter of only one annotation in order to reduce the entire method to an oneliner (on contrary to Spring, no single line of XML is necessary too). – BalusC Feb 23 '16 at 08:11
  • @BalusC Yeah. I have an negative experience with EJB 2.1. So I try to don't use It at all :) And I think real life is more complex than a gigantic business method with automatic transaction management :) – v.ladynev Feb 23 '16 at 08:23
  • EJB2 died a decade ago. Try not spreading the decade-old bad experience then. This only misinforms starters. – BalusC Feb 23 '16 at 08:27
  • @BalusC May be, you are right. A problem is not only with specifications, but with implementations too. For an example, we can have a lot of problems with JEE implementation of some versions of WebSphere. – v.ladynev Feb 23 '16 at 08:41

0 Answers0