Configure Hibernate Without hibernate.cfg.xml
May 10, 2013
In hibernate, database connection can also be achieved without using hibernate.cfg.xml. In hibernate annotation, there is a class named as AnnotationConfiguration. AnnotationConfiguration provides the method to configure database properties. There are different methods of AnnotationConfiguration like .addAnnotatedClass, .addProperties etc. There is .configure() methods which seeks hibernate.cfg, We need not to use .configure() if we are not intended to use hibernate.cfg.
Find the complete example.
HibernateUtil.java
package com.concretepage.util; 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(); } }
User.java
package com.concretepage.persistence; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="user") public class User { @Id @GeneratedValue private int id; @Column(name="name") private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Database Table: User
id name 1 Ankita 2 Renu
Output
Ankita