Discuss Hibernate ”; Previous Next 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. Print Page Previous Next Advertisements ”;
Category: hibernate
Hibernate – Useful Resources
Hibernate – Useful Resources ”; Previous Next The following resources contain additional information on Hibernate. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Spring Framework Mastery Course Best Seller 103 Lectures 8 hours Karthikeya T More Detail Java Web Services Course: Restful API Best Seller 72 Lectures 10 hours Chaand Sheikh More Detail React Native Hybrid Mobile App Project with Spring Boot Most Popular 63 Lectures 4.5 hours Senol Atac More Detail JSP, Servlet, JSLT + Hibernate: A Complete Course 109 Lectures 11 hours Chaand Sheikh More Detail Learn Hibernate Java Framework the Easy way! 65 Lectures 5 hours Karthikeya T More Detail PostgreSQL, PGadmin, SQL Course with Mini Project! 106 Lectures 8 hours Karthikeya T More Detail Print Page Previous Next Advertisements ”;
Hibernate – Caching
Hibernate – Caching ”; Previous Next Caching is a mechanism to enhance the performance of a system. It is a buffer memorythat lies between the application and the database. Cache memory stores recently used data items in order to reduce the number of database hits as much as possible. Caching is important to Hibernate as well. It utilizes a multilevel caching scheme as explained below − First-level Cache The first-level cache is the Session cache and is a mandatory cache through which all requests must pass. The Session object keeps an object under its own power before committing it to the database. If you issue multiple updates to an object, Hibernate tries to delay doing the update as long as possible to reduce the number of update SQL statements issued. If you close the session, all the objects being cached are lost and either persisted or updated in the database. Second-level Cache Second level cache is an optional cache and first-level cache will always be consulted before any attempt is made to locate an object in the second-level cache. The second level cache can be configured on a per-class and per-collection basis and mainly responsible for caching objects across sessions. Any third-party cache can be used with Hibernate. An org.hibernate.cache.CacheProvider interface is provided, which must be implemented to provide Hibernate with a handle to the cache implementation. Query-level Cache Hibernate also implements a cache for query resultsets that integrates closely with the second-level cache. This is an optional feature and requires two additional physical cache regions that hold the cached query results and the timestamps when a table was last updated. This is only useful for queries that are run frequently with the same parameters. The Second Level Cache Hibernate uses first-level cache by default and you have nothing to do to use first-level cache. Let”s go straight to the optional second-level cache. Not all classes benefit from caching, so it”s important to be able to disable the second-level cache. The Hibernate second-level cache is set up in two steps. First, you have to decide which concurrency strategy to use. After that, you configure cache expiration and physical cache attributes using the cache provider. Concurrency Strategies A concurrency strategy is a mediator, which is responsible for storing items of data in the cache and retrieving them from the cache. If you are going to enable a second-level cache, you will have to decide, for each persistent class and collection, which cache concurrency strategy to use. Transactional − Use this strategy for read-mostly data where it is critical to prevent stale data in concurrent transactions, in the rare case of an update. Read-write − Again use this strategy for read-mostly data where it is critical to prevent stale data in concurrent transactions, in the rare case of an update. Nonstrict-read-write − This strategy makes no guarantee of consistency between the cache and the database. Use this strategy if data hardly ever changes and a small likelihood of stale data is not of critical concern. Read-only − A concurrency strategy suitable for data, which never changes. Use it for reference data only. If we are going to use second-level caching for our Employee class, let us add the mapping element required to tell Hibernate to cache Employee instances using read-write strategy. <?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> <cache usage = “read-write”/> <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> The usage=”read-write” attribute tells Hibernate to use a read-write concurrency strategy for the defined cache. Cache Provider Your next step after considering the concurrency strategies, you will use your cache candidate classes to pick a cache provider. Hibernate forces you to choose a single cache provider for the whole application. Sr.No. Cache Name & Description 1 EHCache It can cache in memory or on disk and clustered caching and it supports the optional Hibernate query result cache. 2 OSCache Supports caching to memory and disk in a single JVM with a rich set of expiration policies and query cache support. 3 warmCache A cluster cache based on JGroups. It uses clustered invalidation, but doesn”t support the Hibernate query cache. 4 JBoss Cache A fully transactional replicated clustered cache also based on the JGroups multicast library. It supports replication or invalidation, synchronous or asynchronous communication, and optimistic and pessimistic locking. The Hibernate query cache is supported. Every cache provider is not compatible with every concurrency strategy. The following compatibility matrix will help you choose an appropriate combination. Strategy/Provider Read-only Nonstrictread-write Read-write Transactional EHCache X X X OSCache X X X SwarmCache X X JBoss Cache X X You will specify a cache provider in hibernate.cfg.xml configuration file. We choose EHCache as our second-level cache provider − <?xml version = “1.0” encoding = “utf-8”?> <!DOCTYPE hibernate-configuration SYSTEM “http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd”> <hibernate-configuration> <session-factory> <property name = “hibernate.dialect”> org.hibernate.dialect.MySQLDialect </property> <property name = “hibernate.connection.driver_class”> com.mysql.jdbc.Driver </property> <!–
Hibernate – Criteria Queries
Hibernate – Criteria Queries ”; Previous Next Hibernate provides alternate ways of manipulating objects and in turn data available in RDBMS tables. One of the methods is Criteria API, which allows you to build up a criteria query object programmatically where you can apply filtration rules and logical conditions. The Hibernate Session interface provides createCriteria() method, which can be used to create a Criteria object that returns instances of the persistence object”s class when your application executes a criteria query. Following is the simplest example of a criteria query is one, which will simply return every object that corresponds to the Employee class. Criteria cr = session.createCriteria(Employee.class); List results = cr.list(); Restrictions with Criteria You can use add() method available for Criteria object to add restriction for a criteria query. Following is the example to add a restriction to return the records with salary is equal to 2000 − Criteria cr = session.createCriteria(Employee.class); cr.add(Restrictions.eq(“salary”, 2000)); List results = cr.list(); Following are the few more examples covering different scenarios and can be used as per the requirement − Criteria cr = session.createCriteria(Employee.class); // To get records having salary more than 2000 cr.add(Restrictions.gt(“salary”, 2000)); // To get records having salary less than 2000 cr.add(Restrictions.lt(“salary”, 2000)); // To get records having fistName starting with zara cr.add(Restrictions.like(“firstName”, “zara%”)); // Case sensitive form of the above restriction. cr.add(Restrictions.ilike(“firstName”, “zara%”)); // To get records having salary in between 1000 and 2000 cr.add(Restrictions.between(“salary”, 1000, 2000)); // To check if the given property is null cr.add(Restrictions.isNull(“salary”)); // To check if the given property is not null cr.add(Restrictions.isNotNull(“salary”)); // To check if the given property is empty cr.add(Restrictions.isEmpty(“salary”)); // To check if the given property is not empty cr.add(Restrictions.isNotEmpty(“salary”)); You can create AND or OR conditions using LogicalExpression restrictions as follows − Criteria cr = session.createCriteria(Employee.class); Criterion salary = Restrictions.gt(“salary”, 2000); Criterion name = Restrictions.ilike(“firstNname”,”zara%”); // To get records matching with OR conditions LogicalExpression orExp = Restrictions.or(salary, name); cr.add( orExp ); // To get records matching with AND conditions LogicalExpression andExp = Restrictions.and(salary, name); cr.add( andExp ); List results = cr.list(); Though all the above conditions can be used directly with HQL as explained in previous tutorial. Pagination Using Criteria There are two methods of the Criteria interface for pagination. Sr.No. Method & Description 1 public Criteria setFirstResult(int firstResult) This method takes an integer that represents the first row in your result set, starting with row 0. 2 public Criteria setMaxResults(int maxResults) This method tells Hibernate to retrieve a fixed number maxResults of objects. Using above two methods together, we can construct a paging component in our web or Swing application. Following is the example, which you can extend to fetch 10 rows at a time − Criteria cr = session.createCriteria(Employee.class); cr.setFirstResult(1); cr.setMaxResults(10); List results = cr.list(); Sorting the Results The Criteria API provides the org.hibernate.criterion.Order class to sort your result set in either ascending or descending order, according to one of your object”s properties. This example demonstrates how you would use the Order class to sort the result set − Criteria cr = session.createCriteria(Employee.class); // To get records having salary more than 2000 cr.add(Restrictions.gt(“salary”, 2000)); // To sort records in descening order cr.addOrder(Order.desc(“salary”)); // To sort records in ascending order cr.addOrder(Order.asc(“salary”)); List results = cr.list(); Projections & Aggregations The Criteria API provides the org.hibernate.criterion.Projections class, which can be used to get average, maximum, or minimum of the property values. The Projections class is similar to the Restrictions class, in that it provides several static factory methods for obtaining Projection instances. Following are the few examples covering different scenarios and can be used as per requirement − Criteria cr = session.createCriteria(Employee.class); // To get total row count. cr.setProjection(Projections.rowCount()); // To get average of a property. cr.setProjection(Projections.avg(“salary”)); // To get distinct count of a property. cr.setProjection(Projections.countDistinct(“firstName”)); // To get maximum of a property. cr.setProjection(Projections.max(“salary”)); // To get minimum of a property. cr.setProjection(Projections.min(“salary”)); // To get sum of a property. cr.setProjection(Projections.sum(“salary”)); Criteria Queries 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 the 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>
Hibernate – Batch Processing
Hibernate – Batch Processing ”; Previous Next Consider a situation when you need to upload a large number of records into your database using Hibernate. Following is the code snippet to achieve this using Hibernate − Session session = SessionFactory.openSession(); Transaction tx = session.beginTransaction(); for ( int i=0; i<100000; i++ ) { Employee employee = new Employee(…..); session.save(employee); } tx.commit(); session.close(); By default, Hibernate will cache all the persisted objects in the session-level cache and ultimately your application would fall over with an OutOfMemoryException somewhere around the 50,000th row. You can resolve this problem, if you are using batch processing with Hibernate. To use the batch processing feature, first set hibernate.jdbc.batch_size as batch size to a number either at 20 or 50 depending on object size. This will tell the hibernate container that every X rows to be inserted as batch. To implement this in your code, we would need to do little modification as follows − Session session = SessionFactory.openSession(); Transaction tx = session.beginTransaction(); for ( int i=0; i<100000; i++ ) { Employee employee = new Employee(…..); session.save(employee); if( i % 50 == 0 ) { // Same as the JDBC batch size //flush a batch of inserts and release memory: session.flush(); session.clear(); } } tx.commit(); session.close(); Above code will work fine for the INSERT operation, but if you are willing to make UPDATE operation, then you can achieve using the following code − Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); ScrollableResults employeeCursor = session.createQuery(“FROM EMPLOYEE”).scroll(); int count = 0; while ( employeeCursor.next() ) { Employee employee = (Employee) employeeCursor.get(0); employee.updateEmployee(); seession.update(employee); if ( ++count % 50 == 0 ) { session.flush(); session.clear(); } } tx.commit(); session.close(); Batch Processing Example Let us modify the configuration file to add hibernate.jdbc.batch_size property − <?xml version = “1.0” encoding = “utf-8”?> <!DOCTYPE hibernate-configuration SYSTEM “http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd”> <hibernate-configuration> <session-factory> <property name = “hibernate.dialect”> org.hibernate.dialect.MySQLDialect </property> <property name = “hibernate.connection.driver_class”> com.mysql.jdbc.Driver </property> <!– Assume students is the database name –> <property name = “hibernate.connection.url”> jdbc:mysql://localhost/test </property> <property name = “hibernate.connection.username”> root </property> <property name = “hibernate.connection.password”> root123 </property> <property name = “hibernate.jdbc.batch_size”> 50 </property> <!– List of XML mapping files –> <mapping resource = “Employee.hbm.xml”/> </session-factory> </hibernate-configuration> Consider the following POJO 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; } } Let us create the following EMPLOYEE table to store the 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 the mapping file to map the Employee objects with EMPLOYEE table − <?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 flush() and clear() methods available with Session object so that Hibernate keeps writing these records into the database instead of caching them in the memory. import java.util.*; 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 employee records in batches */ ME.addEmployees( ); } /* Method to create employee records in batches */ public void addEmployees( ){ Session session = factory.openSession(); Transaction tx = null; Integer employeeID = null; try { tx = session.beginTransaction(); for ( int i=0; i<100000; i++ ) { String fname = “First Name ” + i; String lname = “Last Name ” + i; Integer salary = i; Employee employee = new Employee(fname, lname, salary); session.save(employee); if( i % 50 == 0 ) { session.flush(); session.clear(); } } tx.commit(); } catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); } finally { session.close(); } return ; } } 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. Create hibernate.cfg.xml configuration file as explained above. Create Employee.hbm.xml mapping file as shown above. Create Employee.java source file as shown above and compile it. Create ManageEmployee.java source file as shown above and compile it. Execute ManageEmployee binary to run the program, which will create 100000 records in EMPLOYEE table. Print Page Previous Next
Hibernate – Architecture
Hibernate – Architecture ”; Previous Next Hibernate has a layered architecture which helps the user to operate without having to know the underlying APIs. Hibernate makes use of the database and configuration data to provide persistence services (and persistent objects) to the application. Following is a very high level view of the Hibernate Application Architecture. Following is a detailed view of the Hibernate Application Architecture with its important core classes. Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming and Directory Interface (JNDI). JDBC provides a rudimentary level of abstraction of functionality common to relational databases, allowing almost any database with a JDBC driver to be supported by Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE application servers. Following section gives brief description of each of the class objects involved in Hibernate Application Architecture. Configuration Object The Configuration object is the first Hibernate object you create in any Hibernate application. It is usually created only once during application initialization. It represents a configuration or properties file required by the Hibernate. The Configuration object provides two keys components − Database Connection − This is handled through one or more configuration files supported by Hibernate. These files are hibernate.properties and hibernate.cfg.xml. Class Mapping Setup − This component creates the connection between the Java classes and database tables. SessionFactory Object SessionFactory object configures Hibernate for the application using the supplied configuration file and allows for a Session object to be instantiated. The SessionFactory is a thread safe object and used by all the threads of an application. The SessionFactory is a heavyweight object; it is usually created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file. So, if you are using multiple databases, then you would have to create multiple SessionFactory objects. Session Object A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object. The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed. Transaction Object A Transaction represents a unit of work with the database and most of the RDBMS supports transaction functionality. Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA). This is an optional object and Hibernate applications may choose not to use this interface, instead managing transactions in their own application code. StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure(“hibernate.cfg.xml”).build(); Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build(); // Create the SessionFactory Instance SessionFactory factory = meta.getSessionFactoryBuilder().build(); // Create the session Session session = factory.openSession(); // Create the transaction Transaction t = session.beginTransaction(); Query Object Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query. Criteria Object Criteria objects are used to create and execute object oriented criteria queries to retrieve objects. Print Page Previous Next Advertisements ”;
Hibernate – Mapping Types
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 ”;
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 – Configuration
Hibernate – Configuration ”; Previous Next Hibernate requires to know in advance — where to find the mapping information that defines how your Java classes relate to the database tables. Hibernate also requires a set of configuration settings related to database and other related parameters. All such information is usually supplied as a standard Java properties file called hibernate.properties, or as an XML file named hibernate.cfg.xml. I will consider XML formatted file hibernate.cfg.xml to specify required Hibernate properties in my examples. Most of the properties take their default values and it is not required to specify them in the property file unless it is really required. This file is kept in the root directory of your application”s classpath. Hibernate Properties Following is the list of important properties, you will be required to configure for a databases in a standalone situation − Sr.No. Properties & Description 1 hibernate.dialect This property makes Hibernate generate the appropriate SQL for the chosen database. 2 hibernate.connection.driver_class The JDBC driver class. 3 hibernate.connection.url The JDBC URL to the database instance. 4 hibernate.connection.username The database username. 5 hibernate.connection.password The database password. 6 hibernate.connection.pool_size Limits the number of connections waiting in the Hibernate database connection pool. 7 hibernate.connection.autocommit Allows autocommit mode to be used for the JDBC connection. If you are using a database along with an application server and JNDI, then you would have to configure the following properties − Sr.No. Properties & Description 1 hibernate.connection.datasource The JNDI name defined in the application server context, which you are using for the application. 2 hibernate.jndi.class The InitialContext class for JNDI. 3 hibernate.jndi.<JNDIpropertyname> Passes any JNDI property you like to the JNDI InitialContext. 4 hibernate.jndi.url Provides the URL for JNDI. 5 hibernate.connection.username The database username. 6 hibernate.connection.password The database password. Hibernate with MySQL Database MySQL is one of the most popular open-source database systems available today. Let us create hibernate.cfg.xml configuration file and place it in the root of your application”s classpath. You will have to make sure that you have testdb database available in your MySQL database and you have a user test available to access the database. The XML configuration file must conform to the Hibernate 3 Configuration DTD, which is available at http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd. <?xml version=”1.0” encoding=”UTF-8”?> <!DOCTYPE hibernate-configuration PUBLIC “-//Hibernate/Hibernate Configuration DTD 5.3//EN” “http://hibernate.org/dtd/hibernate-configuration-3.0.dtd”> <hibernate-configuration> <session-factory> <property name=”hbm2ddl.auto”>update</property> <property name=”dialect”>org.hibernate.dialect.MySQL8Dialect</property> <property name=”connection.url”>jdbc:mysql://localhost/TUTORIALSPOINT</property> <property name=”connection.username”>root</property> <property name=”connection.password”>guest123</property> <property name=”connection.driver_class”>com.mysql.cj.jdbc.Driver</property> <mapping resource=”employee.hbm.xml”/> </session-factory> </hibernate-configuration> The above configuration file includes <mapping> tags, which are related to hibernatemapping file and we will see in next chapter what exactly a hibernate mapping file is and how and why do we use it? hbm2ddl.auto Property The hbm2ddl.auto property in Hibernate defines how your database schema is handled. Possible values are: create − If the value is ”create”, Hibernate creates a new table in the database when the SessionFactory object is created. In case a table exists in the database with the same name, it deletes the table along with data and creates a new table. update − If the value is ”update”, then Hibernate first validates whether the table is present in the database. If present, it alters that table as per the changes. If not, it creates a new one. validate − If the value is ”validate”, then Hibernate only verifies whether the table is present. If the table does not exist then it throws an exception. create-drop − If the value is ”create-drop”, then Hibernate creates a new table when SessionFactory is created, performs required operations, and deletes the table when SessionFactory is destroyed. This value is used for testing hibernate code. none − It does not make any changes to the schema. Hibernate Dialect A database dialect is a configuration option that allows software to translate general SQL statements into vendor-specific DDL and DML. Different database products, such as PostgreSQL, MySQL, Oracle, and SQL Server, have their own variant of SQL, which are called SQL dialects. Following is the list of various important databases dialect property type − Sr.No. Database & Dialect Property 1 Caché 2007.1 org.hibernate.dialect.Cache71Dialect 2 DB2 org.hibernate.dialect.DB2Dialect 3 DB2/390 org.hibernate.dialect.DB2390Dialect 4 DB2/400 org.hibernate.dialect.DB2400Dialect 5 Cloudscape 10 – aka Derby. org.hibernate.dialect.DerbyDialect 6 Firebird org.hibernate.dialect.FirebirdDialect 7 FrontBase org.hibernate.dialect.FrontBaseDialect 8 H2 org.hibernate.dialect.H2Dialect 9 HSQLDB(HyperSQL) org.hibernate.dialect.HSQLDialect 10 Informix org.hibernate.dialect.InformixDialect 11 Ingres 9.2 org.hibernate.dialect.IngresDialect 12 Ingres 9.3 and later org.hibernate.dialect.Ingres9Dialect 13 Ingres 10 and later org.hibernate.dialect.Ingres10Dialect 14 Interbase org.hibernate.dialect.InterbaseDialect 15 Microsoft SQL Server 2000 org.hibernate.dialect.SQLServerDialect 16 Microsoft SQL Server 2005 org.hibernate.dialect.SQLServerDialect 17 Microsoft SQL Server 2008 org.hibernate.dialect.SQLServer2008Dialect 18 MySQL (prior to 5.x) org.hibernate.dialect.MySQLDialect 19 MySQL 5.x org.hibernate.dialect.MySQL5Dialect 20 Oracle 8i org.hibernate.dialect.Oracle8iDialect 21 Oracle 9i org.hibernate.dialect.Oracle9iDialect 22 Oracle 10g org.hibernate.dialect.Oracle10gDialect 23 Oracle 11g org.hibernate.dialect.Oracle10gDialect