Search This Blog

Monday 5 September 2011

And then they were brought to-ogether

Continuing from the last post, now we need to execute the code. This is where we pass over the control to Hibernate and the framework takes the necessary action to create a database based on the information provided in our mapping files. For this we need to create the cfg file.The cfg or configuration file contains all the configuration information that is needed to get Hibernate up and running.This file must also be present on the class-path.
 hibernate.cfg.xml 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
            "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
            "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.url">
                 jdbc:mysql://localhost:3306/menagerieDb
        </property>
        <property name="hibernate.hbm2ddl.auto">create-drop</property>
        <!-- 
            Setting this property to create-drop will create a brand-new database 
            each time you start the application, which is great for integration tests, 
            but not anywhere else. If you set this value to update, on the other hand, 
            Hibernate will only create the database if it doesn't already exist, 
            and will update any existing tables to match your current domain model.  
         -->        
        <property name="show_sql">true</property>
        
        <mapping resource="com/menagerie/domain/entity/Owner.hbm.xml" />
        <mapping resource="com/menagerie/domain/entity/Pet.hbm.xml" />

    </session-factory>
</hibernate-configuration>
  1. There are available other methods of configuring Hibernate too. 
  2. The cfg file contains the names of the mapping files. These files are read by Hibernate 
  3. The "show_sql" property when set to true will output the generated sq statements to the console or log files (configured output stream). 
  4. As described above in the xml comments the "hibernate.hbm2ddl.auto" property has been set to "create-drop". This instructs Hibernate to drop any tables found in the specified database "menagerieDb" and (re)create the tables specified in the mapping files.
Executing the Code:
public static void main(String[] args) {
    Configuration configuration = new Configuration();
    configuration = configuration.configure();
    configuration.buildSessionFactory();
}
The above code will:
  1. Creates a configuration object. 
  2. This object represents all the Object Relational mappings. It is used to create the Session Factory Object.
  3. The SessionFactory at its simplest, is a factory for hibernate sessions. On execution of Line 3, the DDL scripts are generated and executed. A part of the logs are given below:
Jul 27, 2011 12:06:58 AM org.hibernate.impl.SessionFactoryImpl <init>
INFO: building session factory
Jul 27, 2011 12:06:59 AM org.hibernate.impl.SessionFactoryObjectFactory addInstance
INFO: Not binding factory to JNDI, no JNDI name configured
Jul 27, 2011 12:06:59 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: Running hbm2ddl schema export
Jul 27, 2011 12:06:59 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: exporting generated schema to database
Jul 27, 2011 12:06:59 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: schema export complete
The resultant sql is as follows:
CREATE TABLE `owner` (
  `ID` bigint(20) NOT NULL AUTO_INCREMENT,
  `NAME` varchar(255) DEFAULT NULL,
  `USERID` varchar(255) DEFAULT NULL,
  `MODIFIED_BY` bigint(20) DEFAULT NULL,
  `CREATED_BY` bigint(20) DEFAULT NULL,
  `CREATED_DATE` datetime DEFAULT NULL,
  `MODIFIED_DATE` datetime DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `pet` (
  `ID` bigint(20) NOT NULL,
  `NAME` varchar(255) DEFAULT NULL,
  `AGE` int(11) DEFAULT NULL,
  `TAGID` varchar(255) DEFAULT NULL,
  `OWNER_ID` bigint(20) DEFAULT NULL,
  `MODIFIED_BY` bigint(20) DEFAULT NULL,
  `CREATED_BY` bigint(20) DEFAULT NULL,
  `CREATED_DATE` datetime DEFAULT NULL,
  `MODIFIED_DATE` datetime DEFAULT NULL,
  PRIMARY KEY (`ID`),
  KEY `FK134FF898ED9C3` (`OWNER_ID`),
  CONSTRAINT `FK134FF898ED9C3` FOREIGN KEY (`OWNER_ID`) REFERENCES `owner` (`ID`)
)
Observations:
  1. If we check the data copied from MySQL dump, it does not reflect the unique or not-null constraints that were applied in the mapping files. This issue will be discussed in one of the later blogs. 
  2. Otherwise we are ready to start using the database. If we are not comfortable auto-creating the DDL, then we can write sql scripts manually, create the database and proceed with the application. Care should be taken however that the names in the hbm file match with the column and table names.

No comments:

Post a Comment