I am trying to connect to DB in a servlet using Hibernate.I have read that we can use either hibernate.cfg.xml or hibernate.properties file for configuration of session.For me i
Remove .configure()
if you are using hibernate.properties
. Below code is
HibernateUtil
session factory implementation.
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
ServiceRegistry serviceRegistry
= new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
configuration.addAnnotatedClass(LookUpModel.class);
return configuration
.buildSessionFactory(serviceRegistry);
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("There is issue in hibernate util");
}
}
hibernate.properites file
hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate.connection.url = jdbc:mysql://localhost:3306/test
hibernate.connection.username = root
hibernate.connection.password = passsword
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=50
hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
If you are using a database from a servlet then you should define a DataSource in your server and point one hibernate property at that instead of defining everything via all the other hibernate properties you're probably using now.
This has the benefit of permitting you to define connection pooling and other connection related parameters independently of your application.
For example, your production environment is likely to have a different database password than your test and development environments.
From what i understood from hibernate the best thing to do is to define the mapping in the hibernate.cfg.xml
file and other configurations in the hibernate.properties
.
An alternative approach to configuration is to specify a full configuration in a file named hibernate.cfg.xml
. This file can be used as a replacement for the hibernate.properties
file or, if both are present, to override properties.
The hibernate.cfg.xml
is also more convenient once you have to tune the Hibernate cache. It is your choice to use either hibernate.properties or hibernate.cfg.xml
. Both are equivalent.
You can read more about this in the following link:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html
This code will call hibernate.cfg.xml by default:
Configuration configuration = new Configuration().configure();
And this code will call hibernate.properties by default:
Configuration configuration = new Configuration();
Hope it helps.