How to configure hibernate without configuration file

It’s a common method to use a configuration file where database connection details, mapped entity details are provided which we commonly call as hibernate.cfg.xml or hibernate.properties.
It is a common belief that to start using hibernate we have to use a configuration file. But let me tell you that it is also possible to completely omit this file and configure hibernate alongwith a particular database directly from the code. Let’s see how:

I am going to create a class called HibernateUtil which shall contain the configuration code as below:

  public class HibernateUtil {
    //declare a session factory
    private static final SessionFactory concreteSessionFactory;
    //put all code in static block so that it is initialized at the time of class load
    static {
 try {
  Properties prop= new Properties();
                //provide the required properties
                prop.setProperty("hibernate.connection.url",  "jdbc:mysql://localhost:3306/codippa");
         prop.setProperty("hibernate.connection.username", "root");
  prop.setProperty("hibernate.connection.password", "root");
                prop.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
                //create a configuration
  Configuration config = new Configuration();
  //provide all properties to this configuration
  config.setProperties(prop);
                //add classes which are mapped to database tables.
  config.addAnnotatedClass(Student.class);
  //initialize session factory
  concreteSessionFactory = config.buildSessionFactory();
 } catch (Throwable ex) {
  throw new ExceptionInInitializerError(ex);
 }
  }
  /**
  * Return session for every database transaction from this static method
  */
  public static Session getSession() throws HibernateException {
  return concreteSessionFactory.openSession();
 }
}

Now let’s check the entity class which was referred by the configuration (School.class)

@Entity
@Table(name="student")
public class Student {

 @Id
 @Column(name="id")
 private int id;
 @Column(name="name")
 private String name;
 @Column(name="rollno")
 private int rollNo;

//getters and setters follow

}

Let’s tweak in:

1. addAnnotatedClass method of configuration class returns the same configuration objecy on which it was called. Any number of classes can be added to the configuration by calling this method repeatedly as:
config.addAnnotatedClass(A.class).addAnnotatedClass(B.class).addAnnotatedClass(C.class)…. and so on.
2. For those who favor giving property values outside code, we can achieve that in this approach too.
Simply provide the values such as database connection url, dialect, username etc. in an external property file, load the property file into another property object or System properties and instead of using property values directly use them through System properties as:

static {
  try {
 //load external property file here into System properties
 Properties prop= new Properties();
        //provide the required properties
        prop.setProperty("hibernate.connection.url",
        //instead of value use an external property
        System.getProperty(“url”));
        //create a configuration
 Configuration config = new Configuration();
 //provide all properties to this configuration
 config.setProperties(prop);
        //add classes which are mapped to database tables.
 config.addAnnotatedClass(Student.class);
 //initialize session factory
 concreteSessionFactory = config.buildSessionFactory();
   } catch (Throwable ex) {
 throw new ExceptionInInitializerError(ex);
   }
}

Keep visiting for more. CoDippa !!!

sdasdasd

Leave a Reply