Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

Sunday, January 16, 2011

Many to One mapping in Hibernate

Friday, December 31, 2010

One-to-one mapping in Hibernate

Introduction:



Using Shared Primary Key:


Using Foreign Key:


Using Join Table:

Monday, January 18, 2010

Creating an index on a column using hibernate mapping

Mapping:

 

<property

  name="name"

  column="student_name"

  type="string"

  index="xyz__student_name"/>

 

Table Structure (in PostgreSQL)

 

CREATE TABLE xyz

(

  id bigint NOT NULL,

  student_name character varying(255),

  CONSTRAINT xyz_pkey PRIMARY KEY (id)

)

 

CREATE INDEX xyz__student_name

  ON xyz

  USING btree

  (student_name);

Creating a unique contraint on a column through hibernate mapping

Mapping:

 

<class …>

…

  <natural-id>

    <property

      name="name"

      column="name"

      type="string" />

  </natural-id>

…

</class>

 

Table Structure (in PostgreSQL):

 

CREATE TABLE xyz

(

  id bigint NOT NULL,

  "name" character varying(255) NOT NULL,

  CONSTRAINT xyz_pkey PRIMARY KEY (id),

  CONSTRAINT xyz_name_ukey UNIQUE (name)

)

 

Wednesday, December 23, 2009

Basic Hibernate APIs

      // configure will look for mapping & settings in an application     

      // resource file named hibernate.cfg.xml

      SessionFactory sessionFactory =

            new Configuration().configure().buildSessionFactory();

      Session session = sessionFactory.getCurrentSession();

      try

      {

            session.beginTransaction();

           

            Event testEvent = new Event();

            testEvent.setTitle("testTitle");

           

            session.save(testEvent);

            // Commit if all goes well

            session.getTransaction().commit();

      }

      catch (Exception e )

      {

            // rollback if something fails

            session.getTransaction().rollback();

      }

 

Monday, December 21, 2009

Basic Hibernate Command line application

Here is a basic hibernate command line application that is based on the getting started chapter of Hibernate Reference Documentation. It works with PostgreSQL and can be used to play around with small code changes and seeing the impact on the database. To point to another database, change hibernate.cfg.xml.


To build the application, run

mvn clean install

To execute, run

mvn exec:java -Dexec.mainClass=tutorial.EventManager -Dexec.args="store"

Thursday, October 29, 2009

Introducing a new hibernate persistant entity

1. Write down how your model object (.java file), hibernate mapping (.hbm file) and ER diagram (DB schema) is going to look like before and after the change. Contemplate on the end result and confirm that it is the best solution in each aspect (model, mapping and schema)
2. Implement any new model object. Review (see "Self reviewing code changes").
3. Coin the hbm mapping for the new model object. Review.
4. Modify existing model object to reference the new model object. Review.
5. Modify existing mapping to reference the newly mapped object. Review.
6. Write a new test case that will
a. exercise each method and each control flow (within the methods)
b. exercise each attribute of mapping
7. Make the test case pass (this will automatically rebuild the schema or you might have to drop and recreate the schema manually)
8. Write SQL scripts to
a. Change the schema on production.
b. Migrate existing data.
9. Use the new APIs from client APIs.

Wednesday, October 28, 2009

Hibernate many-to-one example

Basic many-to-one
<class
  name="Student"
  table="STUDENT"> Many students have the same course
  ...
  <many-to-one>
    name="course"
student has a property by name "course"
    column="COURSE_ID" COURSE_ID is a foreign key in STUDENT table.
    "column" is Optional. If not specified, target entity name ("course") + "_" + target entity if property name is default.
    class="Course" Optional. If not specified, hibernate will figure out from type of property.
    not-null="true"/> Each student MUST have a course
</class>

public class Student
{
  private Course course; // with getters and setters
  ...
}

"unique" in many-to-one

<class
  name="Student"
  table="STUDENT">
  ...
  <many-to-one>
    name="course"

    column="COURSE_ID"
    class="Course"

    not-null="true"
    unique="true"/> 
Each student MUST have a UNIQUE course. Does not make  sense in this example as that would mean each student must have a unique course i.e.  only one student can study a course. :-)
</class>


Wednesday, September 09, 2009

Hibernate Schema tools

The hbm2ddl.auto column indicates the values for the hbm2ddl.auto property in the hibernate configuration file

The Purpose column indicates what is the impact of using the specified hbm2ddl.auto value

The Class Name column indicates how to achieve the “purpose” programmatically.

 

hbm2ddl.auto option

Purpose

Class name

create or create-drop or

create – to drop the schema and create it whenever SessionFactory is built

create-drop – to drop the schema when SessionFactory is closed.

 

SchemaExport

e.g.

SchemaExport ex = new SchemaExport( new Configuration().configure() );

Ex.create(false, true);

// false – don’t print sql to stdout

// true – Execute ddl immediately on database

Update

Update – Read the schema through JDBC driver (not reliable) and make schema changes to fit the schema to mappings

SchemaUpdate

e.g.

SchemaUpdate su =

New SchemaUpdate(new Configuration().configure() );

Su.execute(false); // don’t print ddl on stdout

Validate

Validator – compare mapping with metadata and throw exception if they do not match.

SchemaValidator

e.g.

new SchemaValidator(new Configuration().configure()).validate()

 

Hibernate configuration file simple example with explanation in comments

<!DOCTYPE hibernate-configuration SYSTEM

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

      <session-factory>

            <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>

            <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/lab</property>          

            <property name="hibernate.connection.username">meridian</property>

            <property name="hibernate.connection.password">meridian</property>

 

            <!--

             | Which variant of SQL to use 

             +-->

            <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>

 

            <!-- Use the C3P0 connection pool provider -->

            <!--

             | Minimum number of connections in the pool is 5. Atleast 5 connections should

             | be there in the pool

             +-->

            <property name="hibernate.c3p0.min_size">5</property>

            <!--

             | Maximum number of connections in the pool is 20. There are already 20 

             | connections and more connections are requested, then a runtime exception is thrown.

             | This is the only mandatory config. option for c3p0 (connection pool used by

             | hibernate out-of-the-box.

             +-->

            <property name="hibernate.c3p0.max_size">20</property>

            <!--

             | If a connection is not used for 300 seconds, remove it from the pool

             +-->

            <property name="hibernate.c3p0.timeout">300</property>

            <!--

             | Prepared statements are cached for performance benefits. If 50 prepared statements 

             | are cached, the oldest prepared statement is moved out of cache

             +-->

            <property name="hibernate.c3p0.max_statements">50</property>

            <!--

             | If a connection is idle for 3000 seconds, validate it.

             +-->

            <property name="hibernate.c3p0.idle_test_period">3000</property>

 

            <!-- Show and print nice SQL on stdout -->

            <!--

             | 1. Could also be hibernate.show_sql. 'hibernate' prefix is optional in xml files.

             | 2. Refer to org.hibernate.cfg.Environment for a list of all property names

             | 3. This could also be ...name="show_sql">${displaysql}</... Then a system property

             |    by name "displaysql" will have to be defined as in java -displaysql=true 

             +-->

            <property name="show_sql">true</property>

           

            <!--

             | If the same property is specified in a properties file, this would have been

             | hibernate.show_sql = true 

             +-->

            <property name="format_sql">true</property>

 

            <!--

             | List of XML mapping files

             +-->

            <mapping resource="lab/Event.hbm.xml" />

            <mapping resource="lab/Phone.hbm.xml" />

      </session-factory>

</hibernate-configuration>

Tuesday, September 08, 2009

hbm stands for Hibernate metadata model

 

Hibernate term - transactional write-behind

Hibernate, while synchronizing the persistent object changes, optimizes the list of SQL statements issued. This optimization prevents foreign key violations but still be predictable.

Hibernate term - cascading save

When a new instance of a persistence object is created, it does not have to be saved explicitly as long as it is reachable from a already persistent instance.

Hibernate term - Automatic Dirty Checking

Hibernate determines changes made to state of persistent objects during the course of a session (a unit of work with the db) and automatically synchronizes those changes with the persistence store.

Starting HSQL Database manager

Presuming hsqldb.jar is present in the ‘lib’ sub-directory of the current directory,

 

java -classpath ./lib/hsqldb.jar  org.hsqldb.util.DatabaseManagerSwing &

Starting HSQLDB

Presuming hsqldb.jar is present in the ‘lib’ sub-directory of the current directory,

 

java -classpath ./lib/hsqldb.jar  org.hsqldb.server.Server &

Friday, September 04, 2009

Hibernate Getting Started

Source: Hibernate Reference documentation

Hibernate Getting Started


Hibernate Mapping File - Specifies how instances of persistent classes are to be persisted and loaded. This specification is laid out by detailing the properties that are mapped to columns, classes that are mapped to tables and the relationship between classes mapped in DB semantics like foreign keys (and join tables?).

Basic Hibernate Mapping File (there are multiple listings of the same file. Each listing builds upon the previous listing):

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  <!-- This file will first be looked up in classpath, then on the web. -->
<hibernate-mapping package="org.hibernate.tutorial.domain">
[...]
</hibernate-mapping>


<hibernate-mapping package="org.hibernate.tutorial.domain">
  <class name="Event" table="EVENTS">
    <!-- All classes that represent persistent entities, must be mapped to a table -->
    <!-- This tells hibernate to persist and load instances of Event class to the EVENTS table. Each instance of Event is a row in EVENTS table -->
  </class>
</hibernate-mapping>

<hibernate-mapping package="org.hibernate.tutorial.domain">
  <class name="Event" table="EVENTS">
    <id name="id" column="EVENT_ID">
 
    <!--
The class Event bean has a property (or getter and setter) by name "id" that serves as a key or id of Event class. The id has to be stored to the column EVENT_ID. -->
      <generator class="native"/>
        <!-- Use hibernate's key generation strategy (How are identifier values generated?) to generate the Keys for Events. Other strategies include Data base generated keys, Globally unique keys, application generated keys -->
    </id>
  </class>
</hibernate-mapping>

<hibernate-mapping package="org.hibernate.tutorial.domain">
  <class name="Event" table="EVENTS">
    <id name="id" column="EVENT_ID">
      <generator class="native"/>
    </id>
    <!-- Other properties of Event class. If a property is not mapped, it is not considered persistent. -->
    <property name="date" type="timestamp" column="EVENT_DATE"/>
      <!-- Event has a getDate() and setDate() and the value is to be stored in the column named EVENT_DATE. Type is hibernate mapping type. There are converters that convert between Java to SQL data types and visa-versa. If type not specified, hibernate will try to determine the mapping type and conversion type. This automatically (detected through reflection - can impact start up performance) type may not be what you want. For example java.util.Date can map to "date" (only date e.g. July 4th, 2009), "timestamp" (both date and time e.g. July 4th, 2009 10:00:00 HRS) or "time" (only time e.g. 10:00:00 HRS). Then you explictly specify the type -->
    <property name="title"/>
      <!-- Event has a getTitle() and setTitle(). Column name is not specified, so use the property name as the column name. -->
  </class>
</hibernate-mapping>