A really brief intro
Hibernate is one of the most incredible Object Relational Mapper (ORM engine) that we have to make scalable and secure Java Enterprise Applications. Today, I going to explain you, how to configure your session factory field by field in order to have a basic connection to a datasource (in this case using IBM DB2 as database engine).
1) You have to create your datasource and that will depend on which application server you are using, in my case I have configured an IBM DB2 datasource into IBM WebSphere Application Server 8.
2) Create a file called hibernate.cfg.xml in YOUR_WEBAPP/WebContent/WEB-INF/ directory.
3) Copy following example and customize accordingly.
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<!-- Database connection settings -->
<!-- SQL dialect -->
<!-- Disable the second-level cache -->
<!-- Echo all executed SQL to stdout -->
<mapping class="com.base22.awesomeapp.models.User" />
<mapping class="com.base22.awesomeapp.models.Page" />
Basic explanation of properties
|connection.datasource||This is the name of the datasource you configure previously, this configuration depends on your specific application server|
|dialect||A hibernate dialect is a “the variant of a SQL language”. Hibernate can work with many databases engines like: DB2, PostgreSQL, MySQL, Oracle, etc. However, databases have propietary extensions and SQL variations, and of course set or sub-sets of SQL standard implementations, for that reason Hibernate uses “dialect” configuration to know which database you are using and switch to the specific SQL syntax.|
|cache.provider_class||Cache will allow us to store data in memory to the database, using this we will achieve a reduction in traffic between it and our system and also reduce access time to data.The second level cache is associated with the Session Factory object. This allows that an object -which is cached- can be obtained anywhere in the application by any user at any time as often as necessary and without accessing the database.To operate this level, we must do some settings in Hibernate and also choose a cache implementer.
Hibernate supports 4 open-source implementations of cache:
|show_sql||Enables the build-in a function of Hibernate to display all the generated SQL statements to the console.|
|javax.persistence.validation.mode||Hibernate Validator includes an event listener (part of Hibernate Annotations in the org.hibernate.cfg.beanvalidation.BeanValidationEventListener class). It listens for events like: PreInsertEvent, PreUpdateEvent and PreDeleteEvent, verify all the constraints applied to the entities, and throws an exception when a constraint is violated.|
Read more about Hibernate configuration in this link: http://docs.jboss.org/hibernate/orm/4.2/manual/en-US/html/ch01.html#tutorial-firstapp-configuration
And remember, be happy with your code!