0
votes

I'm new to hibernate and I've written the following code,

package main;

import java.util.List;

import model.Message;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.stat.Statistics;

public class Main {

    public static void main(String[] args) throws Exception {
        Configuration configuration = new Configuration().configure();
        SessionFactory factory = configuration.buildSessionFactory();

        Session session = factory.openSession();



        //Transaction transaction = session.beginTransaction();
        List<Message> messages = session.createQuery("from Message").list();

        Message message = new Message();
        message.setMessage("Hello World");

        session.save(message);

        System.out.println(messages);



        System.out.println(session);
        session.close();
        factory.close();
        System.out.println("After the closure");


    }
}

Here I've not begun the transaction and I've closed the session. But Hibernate didn't complain about Transactions. Are there implicit transactions, if so how should I disable them.

1

1 Answers

1
votes

Hibernate didn't had a reason to complain about Transactions. :)

You closed the session after you did the work. You shouldn't create a new sessionFactory for each database edit though:

A SessionFactory is an expensive-to-create, threadsafe object, intended to be shared by all application threads. It is created once, usually on application startup, from a Configuration instance.

A Session is an inexpensive, non-threadsafe object that should be used once and then discarded for: a single request, a conversation or a single unit of work. A Session will not obtain a JDBC Connection, or a Datasource, unless it is needed. It will not consume any resources until used.

Read more about Hibernate transaction management here.