Hibernate – Mapping Types ”; Previous Next When you prepare a Hibernate mapping document, you find that you map the Java data types into RDBMS data types. The types declared and used in the mapping files are not Java data types; they are not SQL database types either. These types are called Hibernate mapping types, which can translate from Java to SQL data types and vice versa. This chapter lists down all the basic, date and time, large object, and various other builtin mapping types. Primitive Types Mapping type Java type ANSI SQL Type integer int or java.lang.Integer INTEGER long long or java.lang.Long BIGINT short short or java.lang.Short SMALLINT float float or java.lang.Float FLOAT double double or java.lang.Double DOUBLE big_decimal java.math.BigDecimal NUMERIC character java.lang.String CHAR(1) string java.lang.String VARCHAR byte byte or java.lang.Byte TINYINT boolean boolean or java.lang.Boolean BIT yes/no boolean or java.lang.Boolean CHAR(1) (”Y” or ”N”) true/false boolean or java.lang.Boolean CHAR(1) (”T” or ”F”) Date and Time Types Mapping type Java type ANSI SQL Type date java.util.Date or java.sql.Date DATE time java.util.Date or java.sql.Time TIME timestamp java.util.Date or java.sql.Timestamp TIMESTAMP calendar java.util.Calendar TIMESTAMP calendar_date java.util.Calendar DATE Binary and Large Object Types Mapping type Java type ANSI SQL Type binary byte[] VARBINARY (or BLOB) text java.lang.String CLOB serializable any Java class that implements java.io.Serializable VARBINARY (or BLOB) clob java.sql.Clob CLOB blob java.sql.Blob BLOB JDK-related Types Mapping type Java type ANSI SQL Type class java.lang.Class VARCHAR locale java.util.Locale VARCHAR timezone java.util.TimeZone VARCHAR currency java.util.Currency VARCHAR Print Page Previous Next Advertisements ”;
Category: hibernate
Hibernate – Mapping Files
Hibernate – Mapping Files ”; Previous Next An Object/relational mappings are usually defined in an XML document. This mapping file instructs Hibernate — how to map the defined class or classes to the database tables? Though many Hibernate users choose to write the XML by hand, but a number of tools exist to generate the mapping document. These include XDoclet, Middlegen and AndroMDA for the advanced Hibernate users. Let us consider our previously defined POJO class whose objects will persist in the table defined in next section. public class Employee { private int id; private String firstName; private String lastName; private int salary; public Employee() {} public Employee(String fname, String lname, int salary) { this.firstName = fname; this.lastName = lname; this.salary = salary; } public int getId() { return id; } public void setId( int id ) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName( String first_name ) { this.firstName = first_name; } public String getLastName() { return lastName; } public void setLastName( String last_name ) { this.lastName = last_name; } public int getSalary() { return salary; } public void setSalary( int salary ) { this.salary = salary; } } There would be one table corresponding to each object you are willing to provide persistence. Consider above objects need to be stored and retrieved into the following RDBMS table − create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id) ); Based on the two above entities, we can define following mapping file, which instructs Hibernate how to map the defined class or classes to the database tables. <?xml version = “1.0” encoding = “utf-8”?> <!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD//EN” “http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd”> <hibernate-mapping> <class name = “Employee” table = “EMPLOYEE”> <meta attribute = “class-description”> This class contains the employee detail. </meta> <id name = “id” type = “int” column = “id”> <generator class=”native”/> </id> <property name = “firstName” column = “first_name” type = “string”/> <property name = “lastName” column = “last_name” type = “string”/> <property name = “salary” column = “salary” type = “int”/> </class> </hibernate-mapping> You should save the mapping document in a file with the format <classname>.hbm.xml. We saved our mapping document in the file Employee.hbm.xml. Let us see understand a little detail about the mapping elements used in the mapping file − The mapping document is an XML document having <hibernate-mapping> as the root element, which contains all the <class> elements. The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute. The <meta> element is optional element and can be used to create the class description. The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type. The <generator> element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to native to let hibernate pick up either identity, sequence, or hilo algorithm to create primary key depending upon the capabilities of the underlying database. The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type. There are other attributes and elements available, which will be used in a mapping document and I would try to cover as many as possible while discussing other Hibernate related topics. Generator A generator class is used to generate an ID for the for an object, which is going to be the primary key of the database table. All generator classes implement org.hibernate.id.IdentifierGenerator interface. One can create their own generator class by implementing the above-mentioned interface and overriding the generator(SharedSessionContractImplementor sess, Object obj) method. Check the employee.hbm.xml file snippet below: <hibernate-mapping> <class name=”com.mypackage.Employee” table=”emp”> <id name=”id”> <generator class=”assigned”></generator> </id> … </hibernate-mapping> Types of Generator Classes Hibernate provides many predefined generator classes. Some of the important predefined generator classes in hibernate are: Print Page Previous Next Advertisements ”;
Hibernate – O/R Mappings
Hibernate – O/R Mappings ”; Previous Next So far, we have seen very basic O/R mapping using hibernate, but there are three most important mapping topics, which we have to learn in detail. These are − Mapping of collections, Mapping of associations between entity classes, and Component Mappings. Collections Mappings If an entity or class has collection of values for a particular variable, then we can map those values using any one of the collection interfaces available in java. Hibernate can persist instances of java.util.Map, java.util.Set, java.util.SortedMap, java.util.SortedSet, java.util.List, and any array of persistent entities or values. Sr.No. Collection type & Mapping Description 1 java.util.Set This is mapped with a <set> element and initialized with java.util.HashSet 2 java.util.SortedSet This is mapped with a <set> element and initialized with java.util.TreeSet. The sort attribute can be set to either a comparator or natural ordering. 3 java.util.List This is mapped with a <list> element and initialized with java.util.ArrayList 4 java.util.Collection This is mapped with a <bag> or <ibag> element and initialized with java.util.ArrayList 5 java.util.Map This is mapped with a <map> element and initialized with java.util.HashMap 6 java.util.SortedMap This is mapped with a <map> element and initialized with java.util.TreeMap. The sort attribute can be set to either a comparator or natural ordering. Arrays are supported by Hibernate with <primitive-array> for Java primitive value types and <array> for everything else. However, they are rarely used, so I am not going to discuss them in this tutorial. If you want to map a user defined collection interfaces, which is not directly supported by Hibernate, you need to tell Hibernate about the semantics of your custom collections, which is not very easy and not recommend to be used. Association Mappings The mapping of associations between entity classes and the relationships between tables is the soul of ORM. Following are the four ways in which the cardinality of the relationship between the objects can be expressed. An association mapping can be unidirectional as well as bidirectional. Sr.No. Mapping type & Description 1 Many-to-One Mapping many-to-one relationship using Hibernate 2 One-to-One Mapping one-to-one relationship using Hibernate 3 One-to-Many Mapping one-to-many relationship using Hibernate 4 Many-to-Many Mapping many-to-many relationship using Hibernate Component Mappings It is very much possible that an Entity class can have a reference to another class as a member variable. If the referred class does not have its own life cycle and completely depends on the life cycle of the owning entity class, then the referred class hence therefore is called as the Component class. The mapping of Collection of Components is also possible in a similar way just as the mapping of regular Collections with minor configuration differences. We will see these two mappings in detail with examples. Sr.No. Mapping type & Description 1 Component Mappings Mapping for a class having a reference to another class as a member variable. Print Page Previous Next Advertisements ”;
Hibernate – Overview
Hibernate – Overview ”; Previous Next Hibernate is an Object-Relational Mapping (ORM) solution for JAVA. It is an open source persistent framework created by Gavin King in 2001. It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieves the developer from 95% of common data persistence related programming tasks. Hibernate sits between traditional Java objects and database server to handle all the works in persisting those objects based on the appropriate O/R mechanisms and patterns. Hibernate Advantages Hibernate takes care of mapping Java classes to database tables using XML files and without writing any line of code. Provides simple APIs for storing and retrieving Java objects directly to and from the database. If there is change in the database or in any table, then you need to change the XML file properties only. Abstracts away the unfamiliar SQL types and provides a way to work around familiar Java Objects. Hibernate does not require an application server to operate. Manipulates Complex associations of objects of your database. Minimizes database access with smart fetching strategies. Provides simple querying of data. Supported Databases Hibernate supports almost all the major RDBMS. Following is a list of few of the database engines supported by Hibernate − HSQL Database Engine DB2/NT MySQL PostgreSQL FrontBase Oracle Microsoft SQL Server Database Sybase SQL Server Informix Dynamic Server Supported Technologies Hibernate supports a variety of other technologies, including − XDoclet Spring J2EE Eclipse plug-ins Maven Print Page Previous Next Advertisements ”;
Hibernate – Persistent Class
Hibernate – Persistent Class ”; Previous Next The entire concept of Hibernate is to take the values from Java class attributes and persist them to a database table. A mapping document helps Hibernate in determining how to pull the values from the classes and map them with table and associated fields. Java classes whose objects or instances will be stored in database tables are called persistent classes in Hibernate. Hibernate works best if these classes follow some simple rules, also known as the Plain Old Java Object (POJO) programming model. There are following main rules of persistent classes, however, none of these rules are hard requirements − All Java classes that will be persisted need a default constructor. All classes should contain an ID in order to allow easy identification of your objects within Hibernate and the database. This property maps to the primary key column of a database table. All attributes that will be persisted should be declared private and have getXXX and setXXX methods defined in the JavaBean style. A central feature of Hibernate, proxies, depends upon the persistent class being either non-final, or the implementation of an interface that declares all public methods. All classes that do not extend or implement some specialized classes and interfaces required by the EJB framework. The POJO name is used to emphasize that a given object is an ordinary Java Object, not a special object, and in particular not an Enterprise JavaBean. Simple POJO Example Based on the few rules mentioned above, we can define a POJO class as follows − public class Employee { private int id; private String firstName; private String lastName; private int salary; public Employee() {} public Employee(String fname, String lname, int salary) { this.firstName = fname; this.lastName = lname; this.salary = salary; } public int getId() { return id; } public void setId( int id ) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName( String first_name ) { this.firstName = first_name; } public String getLastName() { return lastName; } public void setLastName( String last_name ) { this.lastName = last_name; } public int getSalary() { return salary; } public void setSalary( int salary ) { this.salary = salary; } } Print Page Previous Next Advertisements ”;
Hibernate – Home
Hibernate Tutorial PDF Version Quick Guide Resources Job Search Discussion Hibernate is a high-performance Object/Relational persistence and query service, which is licensed under the open source GNU Lesser General Public License (LGPL) and is free to download. Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities. This tutorial will teach you how to use Hibernate to develop your database based web applications in simple and easy steps. Audience This tutorial is designed for all those Java programmers who would like to understand the Hibernate framework and its API. Prerequisites We assume you have a good understanding of the Java programming language. A basic understanding of relational databases, JDBC, and SQL will be very helpful in understanding this tutorial. Print Page Previous Next Advertisements ”;
Hibernate – Examples
Hibernate – Examples ”; Previous Next Let us now take an example to understand how we can use Hibernate to provide Java persistence in a standalone application. We will go through the different steps involved in creating a Java Application using Hibernate technology. Create POJO Classes The first step in creating an application is to build the Java POJO class or classes, depending on the application that will be persisted to the database. Let us consider our Employee class with getXXX and setXXX methods to make it JavaBeans compliant class. A POJO (Plain Old Java Object) is a Java object that doesn”t extend or implement some specialized classes and interfaces respectively required by the EJB framework. All normal Java objects are POJO. When you design a class to be persisted by Hibernate, it is important to provide JavaBeans compliant code as well as one attribute, which would work as index like id attribute in the Employee class. public class Employee { private int id; private String firstName; private String lastName; private int salary; public Employee() {} public Employee(String fname, String lname, int salary) { this.firstName = fname; this.lastName = lname; this.salary = salary; } public int getId() { return id; } public void setId( int id ) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName( String first_name ) { this.firstName = first_name; } public String getLastName() { return lastName; } public void setLastName( String last_name ) { this.lastName = last_name; } public int getSalary() { return salary; } public void setSalary( int salary ) { this.salary = salary; } } Create Database Tables Second step would be creating tables in your database. There would be one table corresponding to each object, you are willing to provide persistence. Consider above objects need to be stored and retrieved into the following RDBMS table − create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id) ); Create Mapping Configuration File This step is to create a mapping file that instructs Hibernate how to map the defined class or classes to the database tables. <?xml version = “1.0” encoding = “utf-8”?> <!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD//EN” “http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd”> <hibernate-mapping> <class name = “Employee” table = “EMPLOYEE”> <meta attribute = “class-description”> This class contains the employee detail. </meta> <id name = “id” type = “int” column = “id”> <generator class=”native”/> </id> <property name = “firstName” column = “first_name” type = “string”/> <property name = “lastName” column = “last_name” type = “string”/> <property name = “salary” column = “salary” type = “int”/> </class> </hibernate-mapping> You should save the mapping document in a file with the format <classname>.hbm.xml. We saved our mapping document in the file Employee.hbm.xml. Let us see little detail about the mapping document − The mapping document is an XML document having <hibernate-mapping> as the root element which contains all the <class> elements. The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute. The <meta> element is optional element and can be used to create the class description. The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type. The <generator> element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to native to let hibernate pick up either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database. The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type. There are other attributes and elements available, which will be used in a mapping document and I would try to cover as many as possible while discussing other Hibernate related topics. Create Application Class Finally, we will create our application class with the main() method to run the application. We will use this application to save few Employee”s records and then we will apply CRUD operations on those records. import java.util.List; import java.util.Date; import java.util.Iterator; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class ManageEmployee { private static SessionFactory factory; public static void main(String[] args) { try { factory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { System.err.println(“Failed to create sessionFactory object.” + ex); throw new ExceptionInInitializerError(ex); } ManageEmployee ME = new ManageEmployee(); /* Add few employee records in database */ Integer empID1 = ME.addEmployee(“Zara”, “Ali”, 1000); Integer empID2 = ME.addEmployee(“Daisy”, “Das”, 5000); Integer empID3 = ME.addEmployee(“John”, “Paul”, 10000); /* List down all the employees */ ME.listEmployees(); /* Update employee”s records */ ME.updateEmployee(empID1, 5000); /* Delete an employee from the database */ ME.deleteEmployee(empID2); /* List down new list of the employees */ ME.listEmployees(); } /* Method to CREATE an employee in the database */ public Integer addEmployee(String fname, String lname, int salary){ Session
Hibernate – Native SQL
Hibernate – Native SQL ”; Previous Next You can use native SQL to express database queries if you want to utilize database-specific features such as query hints or the CONNECT keyword in Oracle. Hibernate 3.x allows you to specify handwritten SQL, including stored procedures, for all create, update, delete, and load operations. Your application will create a native SQL query from the session with the createSQLQuery() method on the Session interface − public SQLQuery createSQLQuery(String sqlString) throws HibernateException After you pass a string containing the SQL query to the createSQLQuery() method, you can associate the SQL result with either an existing Hibernate entity, a join, or a scalar result using addEntity(), addJoin(), and addScalar() methods respectively. Scalar Queries The most basic SQL query is to get a list of scalars (values) from one or more tables. Following is the syntax for using native SQL for scalar values − String sql = “SELECT first_name, salary FROM EMPLOYEE”; SQLQuery query = session.createSQLQuery(sql); query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP); List results = query.list(); Entity Queries The above queries were all about returning scalar values, basically returning the “raw” values from the result set. Following is the syntax to get entity objects as a whole from a native sql query via addEntity(). String sql = “SELECT * FROM EMPLOYEE”; SQLQuery query = session.createSQLQuery(sql); query.addEntity(Employee.class); List results = query.list(); Named SQL Queries Following is the syntax to get entity objects from a native sql query via addEntity() and using named SQL query. String sql = “SELECT * FROM EMPLOYEE WHERE id = :employee_id”; SQLQuery query = session.createSQLQuery(sql); query.addEntity(Employee.class); query.setParameter(“employee_id”, 10); List results = query.list(); Native SQL Example Consider the following POJO class − public class Employee { private int id; private String firstName; private String lastName; private int salary; public Employee() {} public Employee(String fname, String lname, int salary) { this.firstName = fname; this.lastName = lname; this.salary = salary; } public int getId() { return id; } public void setId( int id ) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName( String first_name ) { this.firstName = first_name; } public String getLastName() { return lastName; } public void setLastName( String last_name ) { this.lastName = last_name; } public int getSalary() { return salary; } public void setSalary( int salary ) { this.salary = salary; } } Let us create the following EMPLOYEE table to store Employee objects − create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id) ); Following will be mapping file − <?xml version = “1.0” encoding = “utf-8”?> <!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD//EN” “http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd”> <hibernate-mapping> <class name = “Employee” table = “EMPLOYEE”> <meta attribute = “class-description”> This class contains the employee detail. </meta> <id name = “id” type = “int” column = “id”> <generator class=”native”/> </id> <property name = “firstName” column = “first_name” type = “string”/> <property name = “lastName” column = “last_name” type = “string”/> <property name = “salary” column = “salary” type = “int”/> </class> </hibernate-mapping> Finally, we will create our application class with the main() method to run the application where we will use Native SQL queries − import java.util.*; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.SessionFactory; import org.hibernate.SQLQuery; import org.hibernate.Criteria; import org.hibernate.Hibernate; import org.hibernate.cfg.Configuration; public class ManageEmployee { private static SessionFactory factory; public static void main(String[] args) { try { factory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { System.err.println(“Failed to create sessionFactory object.” + ex); throw new ExceptionInInitializerError(ex); } ManageEmployee ME = new ManageEmployee(); /* Add few employee records in database */ Integer empID1 = ME.addEmployee(“Zara”, “Ali”, 2000); Integer empID2 = ME.addEmployee(“Daisy”, “Das”, 5000); Integer empID3 = ME.addEmployee(“John”, “Paul”, 5000); Integer empID4 = ME.addEmployee(“Mohd”, “Yasee”, 3000); /* List down employees and their salary using Scalar Query */ ME.listEmployeesScalar(); /* List down complete employees information using Entity Query */ ME.listEmployeesEntity(); } /* Method to CREATE an employee in the database */ public Integer addEmployee(String fname, String lname, int salary){ Session session = factory.openSession(); Transaction tx = null; Integer employeeID = null; try { tx = session.beginTransaction(); Employee employee = new Employee(fname, lname, salary); employeeID = (Integer) session.save(employee); tx.commit(); } catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); } finally { session.close(); } return employeeID; } /* Method to READ all the employees using Scalar Query */ public void listEmployeesScalar( ){ Session session = factory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); String sql = “SELECT first_name, salary FROM EMPLOYEE”; SQLQuery query = session.createSQLQuery(sql); query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP); List data = query.list(); for(Object object : data) { Map row = (Map)object; System.out.print(“First Name: ” + row.get(“first_name”)); System.out.println(“, Salary: ” + row.get(“salary”)); } tx.commit(); } catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); } finally { session.close(); } } /* Method to READ all the employees using Entity Query */ public void listEmployeesEntity( ){ Session session = factory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); String sql = “SELECT * FROM EMPLOYEE”; SQLQuery query = session.createSQLQuery(sql); query.addEntity(Employee.class); List employees = query.list(); for (Iterator iterator = employees.iterator(); iterator.hasNext();){ Employee employee = (Employee) iterator.next(); System.out.print(“First Name: ” + employee.getFirstName()); System.out.print(” Last Name: ” + employee.getLastName()); System.out.println(” Salary: ” + employee.getSalary()); } tx.commit(); } catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); } finally { session.close(); } } } Compilation and Execution Here are the steps to compile and run the above mentioned application. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.