How can I create a Hibernate session without hiberante.cfg.xml file?

3.6k views Asked by At

This is my first time using Hiberante.

I am trying to create a Hibernate session within my application using the following:

Session session = HiberanteUtil.getSessionFactory().openSession();

It gives me this error:

org.hibernate.HibernateException: /hibernate.cfg.xml not found

However I do not have a hibernate.cfg.xml file within my project.

How can I create a session without having this file?

2

There are 2 answers

0
v.ladynev On BEST ANSWER

The simples way to configure Hibernate 4 or Hibernate 5

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

Hibernate reads a configuration from hibernate.cfg.xml and hibernate.properties.

You shouldn't call configure(), if you don't want to read hibernate.cfg.xml. With adding an annotated class

SessionFactory sessionFactory = new Configuration()
    .addAnnotatedClass(User.class).buildSessionFactory();
7
P S M On
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import com.concretepage.persistence.User;

public class HibernateUtil {
    private static final SessionFactory concreteSessionFactory;
    static {
        try {
            Properties prop= new Properties();
            prop.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");
            prop.setProperty("hibernate.connection.username", "root");
            prop.setProperty("hibernate.connection.password", "");
            prop.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");

            concreteSessionFactory = new AnnotationConfiguration()
           .addPackage("com.concretepage.persistence")
                   .addProperties(prop)
                   .addAnnotatedClass(User.class)
                   .buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static Session getSession()
            throws HibernateException {
        return concreteSessionFactory.openSession();
    }

    public static void main(String... args){
        Session session=getSession();
        session.beginTransaction();
        User user=(User)session.get(User.class, new Integer(1));
        System.out.println(user.getName());
        session.close();
    }
    }