{"id":38731,"date":"2015-03-31T10:00:15","date_gmt":"2015-03-31T07:00:15","guid":{"rendered":"http:\/\/www.javacodegeeks.com\/?p=38731"},"modified":"2023-12-05T15:39:07","modified_gmt":"2023-12-05T13:39:07","slug":"hibernate-tutorial","status":"publish","type":"post","link":"https:\/\/www.javacodegeeks.com\/2015\/03\/hibernate-tutorial.html","title":{"rendered":"Hibernate Tutorial \u2013 The ULTIMATE Guide (PDF Download)"},"content":{"rendered":"<p><em><strong>EDITORIAL NOTE:<\/strong> In this post, we feature a comprehensive Hibernate Tutorial. Hibernate ORM (Hibernate in short) is an object-relational mapping framework, facilitating the conversion of an object-oriented domain model to a traditional relational database. Hibernate solves the object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions.<\/em><\/p>\n<p><em>Hibernate is one of the most popular Java frameworks out there. For this reason we have provided an abundance of tutorials here at Java Code Geeks, most of which can be found <a href=\"http:\/\/www.javacodegeeks.com\/tutorials\/java-tutorials\/enterprise-java-tutorials\/#Hibernate\">here<\/a>.<\/em><\/p>\n<p><em>Now, we wanted to create a standalone, reference post to provide a framework on how to work with Hibernate and help you quickly kick-start your Hibernate applications. Enjoy!<\/em><\/p>\n<div class=\"toc\">\n<h3>Table Of Contents<\/h3>\n<dl>\n<dt><a href=\"#introduction\">1. Introduction<\/a><\/dt>\n<dt><a href=\"#setup\">2. Project setup<\/a><\/dt>\n<dt><a href=\"#basics\">3. Basics<\/a><\/dt>\n<dd>\n<dl>\n<dt><a href=\"#sessionmanager\">3.1. SessionFactory and Session<\/a><\/dt>\n<dt><a href=\"#transactions\">3.2. Transactions<\/a><\/dt>\n<dt><a href=\"#tables\">3.3. Tables<\/a><\/dt>\n<\/dl>\n<\/dd>\n<dt><a href=\"#intheritance\">4. Inheritance<\/a><\/dt>\n<dt><a href=\"#relationships\">5. Relationships<\/a><\/dt>\n<dd>\n<dl>\n<dt><a href=\"#relationships_onetoone\">5.1. OneToOne<\/a><\/dt>\n<dt><a href=\"#relationships_onetomany\">5.2. OneToMany<\/a><\/dt>\n<dt><a href=\"#relationships_manytomany\">5.3. ManyToMany<\/a><\/dt>\n<dt><a href=\"#relationships_components\">5.4. Components<\/a><\/dt>\n<\/dl>\n<\/dd>\n<dt><a href=\"#dataTypes\">6. User-defined Data Types<\/a><\/dt>\n<dt><a href=\"#interceptors\">7. Interceptors<\/a><\/dt>\n<dt><a href=\"#download\">8. Download<\/a><\/dt>\n<\/dl>\n<\/div>\n<h2><a name=\"introduction\"><\/a>Introduction<\/h2>\n<p>Hibernate is one of the most popular Object\/Relational Mapping (ORM) framework in the Java world. It allows developers to map the object structures of normal Java classes to the relational structure of a database. With the help of an ORM framework the work to store data from object instances in memory to a persistent data store and load them back into the same object structure becomes significantly easier.<\/p>\n<p>At the same time ORM solutions like Hibernate aim to abstract from the specific product used to store the data. This allows using the same Java code with different database products without the need to write code that handles the subtle differences between the supported products.<\/p>\n<p>Hibernate is also a JPA provider, that means it implements the <a href=\"http:\/\/www.javacodegeeks.com\/2015\/02\/jpa-tutorial.html\">Java Persistence API (JPA)<\/a>. JPA is a vendor independent specification for mapping Java objects to the tables of relational databases. As another article of the Ultimate series already addresses the JPA, this article focuses on Hibernate and therefore does not use the JPA annotations but rather the Hibernate specific configuration files.<\/p>\n<p>Hibernate consists of three different components:<\/p>\n<ul>\n<li><strong>Entities<\/strong>: The classes that are mapped by Hibernate to the tables of a relational database system are simple Java classes (Plain Old Java Objects).<\/li>\n<li><strong>Object-relational metadata<\/strong>: The information how to map the entities to the relational database is either provided by annotations (since Java 1.5) or by legacy XML-based configuration files. The information in these files is used at runtime to perform the mapping to the data store and back to the Java objects.<\/li>\n<li><strong>Hibernate Query Language (HQL)<\/strong>: When using Hibernate, queries send to the database do not have to be formulated in native SQL but can be specified using Hibernate&#8217;s query language. As these queries are translated at runtime into the currently used dialect of the chose product, queries formulated in HQL are independent from the SQL dialect of a specific vendor.<\/li>\n<\/ul>\n<p>In this tutorial we are going through different aspects of the framework and will develop a simple Java SE application that stores and retrieves data in\/from a relational database. We will use the following libraries\/environments:<\/p>\n<ul>\n<li>maven &gt;= 3.0 as build environment<\/li>\n<li>Hibernate(4.3.8.Final)<\/li>\n<li>H2 as relational database (1.3.176)<\/li>\n<\/ul>\n<h2><a name=\"setup\"><\/a>Project setup<\/h2>\n<p>As a first step we will create a simple maven project on the command line:<\/p>\n<pre class=\"brush:bash\">mvn archetype:create -DgroupId=com.javacodegeeks.ultimate -DartifactId=hibernate\n<\/pre>\n<p>This command will create the following structure in the file system:<\/p>\n<pre class=\"brush:bash\">|-- src\n|   |-- main\n|   |   `-- java\n|   |       `-- com \n|   |           `-- javacodegeeks\n|   |\t\t\t     `-- ultimate\n|   `-- test\n|   |   `-- java\n|   |       `-- com \n|   |           `-- javacodegeeks\n|   |\t\t\t     `-- ultimate\n`-- pom.xml\n<\/pre>\n<p>The libraries our implementation depends on are added to the dependencies section of the <code>pom.xml<\/code> file in the following way:<\/p>\n<pre class=\"brush:xml\">\t1.3.176\n\t4.3.8.Final\n\n\n\n\t\n\t\tcom.h2database\n\t\th2\n\t\t${h2.version}\n\t\n\t\n\t\torg.hibernate\n\t\thibernate-core\n\t\t${hibernate.version}\n\t\n\n<\/pre>\n<p>To get a better overview of the separate versions, we define each version as a maven property and reference it later on in the dependencies section.<\/p>\n<h2><a name=\"basics\"><\/a>3. Basics<\/h2>\n<h3><a name=\"sessionmanager\"><\/a>3.1. SessionFactory and Session<\/h3>\n<p>Now we cat start to implement our first O\/R mapping. Let&#8217;s start with a simple class that provides a <code>run()<\/code> method that is invoked in the application&#8217;s <code>main<\/code> method:<\/p>\n<pre class=\"brush:java\">public class Main {\n\tprivate static final Logger LOGGER = Logger.getLogger(\"Hibernate-Tutorial\");\n\n\tpublic static void main(String[] args) {\n\t\tMain main = new Main();\n\t\tmain.run();\n\t}\n\n\tpublic void run() {\n\t\tSessionFactory sessionFactory = null;\n\t\tSession session = null;\n\t\ttry {\n\t\t\tConfiguration configuration = new Configuration();\n\t\t\tconfiguration.configure(\"hibernate.cfg.xml\");\n\t\t\tServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();\n\t\t\tsessionFactory = configuration.buildSessionFactory(serviceRegistry);\n\t\t\tsession = sessionFactory.openSession();\n\t\t\tpersistPerson(session);\n\t\t} catch (Exception e) {\n\t\t\tLOGGER.log(Level.SEVERE, e.getMessage(), e);\n\t\t} finally {\n\t\t\tif (session != null) {\n\t\t\t\tsession.close();\n\t\t\t}\n\t\t\tif (sessionFactory != null) {\n\t\t\t\tsessionFactory.close();\n\t\t\t}\n\t\t}\n\t}\n\t...\n<\/pre>\n<p>The <code>run()<\/code> method creates a new instance of the class <code>org.hibernate.cfg.Configuration<\/code> that is subsequently configured using the XML file <code>hibernate.cfg.xml<\/code>. Placing the configuration file in the folder <code>src\/main\/resources<\/code> of our project lets maven put it to the root of the created jar file. This way the file is found at runtime on the classpath.<\/p>\n<p>As a second step the <code>run()<\/code> method constructs a <code>ServiceRegistry<\/code> that uses the previously loaded configuration. An instance of this <code>ServiceRegistry<\/code> can now be passed as an argument to the method <code>buildSessionFactroy()<\/code> of the <code>Configuration<\/code>. This <code>SessionFactory<\/code> can now be used to obtain the session needed to store and load entities to the underlying data store.<\/p>\n<p>The configuration file <code>hibernate.cfg.xml<\/code> has the following content:<\/p>\n<pre class=\"brush:xml\"><!--?xml version='1.0' encoding='utf-8'?-->\n\n\n\n    \n        org.h2.Driver\n        jdbc:h2:~\/hibernate;AUTOCOMMIT=OFF\n        \n        \n        1\n        org.hibernate.dialect.H2Dialect\n        thread\n        org.hibernate.cache.internal.NoCacheProvider\n        true\n        true\n        create\n        \n    \n\n<\/pre>\n<p>As we see from the example above, the configuration file defines a set of properties for the session factory. The first property <code>connection.driver_class<\/code> specifies the database driver that should be used. In our example this is the driver for the H2 database. Through the property <code>connection.url<\/code>, the JDBC-URL is specified. In our case defines that we want to use h2 and that the single database file where H2 stores its data should be located in the home directory of the user and should be named <code>hibernate<\/code> (<code>~\/hibernate<\/code>). As we want to commit our transactions in the example code on our own, we also define the H2 specific configuration option <code>AUTOCOMMIT=OFF<\/code>.<\/p>\n<p>Next the configuration file defines the username and password for the database connection as well as the size of the connection pool. Our sample application just executes code in one single thread, therefore we can set the pool size to one. In cases of an application that has to deal with multiple threads and users, an appropriate pool size has to be chosen.<\/p>\n<p>The property <code>dialect<\/code> specifies a Java class that performs the translation into the database specific SQL dialect.<\/p>\n<p>As of version 3.1, Hibernate provides a method named <code>SessionFactory.getCurrentSession()<\/code> that allows the developer to obtain a reference to the current session. With the configuration property <code>current_session_context_class<\/code> it can be configured where Hibernate should obtain this session from. The default value for this property is <code>jta<\/code> meaning that Hibernate obtains the session from the underlying Java Transaction API (JTA). As we are not using JTA in this sample, we instruct Hibernate with the configuration value <code>thread<\/code> to store and retrieve the session to\/from the current thread.<\/p>\n<p>For the sake of simplicity, we do not want to utilize an entity cache. Hence we set the property <code>cache.provider_class<\/code> to <code>org.hibernate.cache.internal.NoCacheProvider<\/code>.<\/p>\n<p>The following two options tell Hibernate to print out each SQL statement to the console and to format it for better readability. In order to relieve us for development purposes from the burden to create the schema manually, we instruct Hibernate with the option <code>hbm2ddl.auto<\/code> set to <code>create<\/code> to create all tables during startup.<\/p>\n<p>Last but not least we define a mapping resource file that contains all the mapping information for our application. The content of this file will be explained in the following sections.<\/p>\n<p>As mentioned above, the session is used to communicate with the data store and actually represents a JDBC connection. This means all interaction with the connection is done through the session. It is single-threaded and provides a cache for all objects it has up to now worked with. Therefore each thread in the application should work with its own session that it obtains from the session factory.<\/p>\n<p>In contrast to the session, the session factory is thread-safe and provides an immutable cache for the define mappings. For each database there is exactly one session factory. Optionally, the session factory can provide in addition to the session&#8217;s first level cache an application wide second level cache.<\/p>\n<h3><a name=\"transactions\"><\/a>3.2. Transactions<\/h3>\n<p>In the <code>hibernate.cfg.xml<\/code> configuration file we have configured to manage transactions on our own. Hence we have to manually start and commit or rollback every transaction. The following code demonstrates how to obtain a new transaction from the session and how to start and commit it:<\/p>\n<pre class=\"brush:java\">try {\n\tTransaction transaction = session.getTransaction();\n\ttransaction.begin();\n\t...\n\ttransaction.commit();\n} catch (Exception e) {\n\tif (session.getTransaction().isActive()) {\n\t\tsession.getTransaction().rollback();\n\t}\n\tthrow e;\n}\n<\/pre>\n<p>In the first step we call <code>getTransaction()<\/code> in order to retrieve a reference for a new transaction. This transaction is immediately started by invoking the method <code>begin()<\/code> on it. If the following code proceeds without any exception, the transaction gets committed. In case an exception occurred and the current transaction is active, the transaction is rolled back.<\/p>\n<p>As the code shown above is the same for all upcoming examples, it is not repeated in the exact form again and again. The steps to refactor the code into a re-usable form, using for example the template pattern, are left for the reader.<\/p>\n<h3><a name=\"entitymanager\"><\/a>3.3. Tables<\/h3>\n<p>Now that we have learned about session factories, sessions and transactions, it is time to start with the first class mapping. In order to have an easy start, we choose a simple class with only a few simple attributes:<\/p>\n<pre class=\"brush:java\">public class Person {\n\tprivate Long id;\n\tprivate String firstName;\n\tprivate String lastName;\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getFirstName() {\n\t\treturn firstName;\n\t}\n\n\tpublic void setFirstName(String firstName) {\n\t\tthis.firstName = firstName;\n\t}\n\n\tpublic String getLastName() {\n\t\treturn lastName;\n\t}\n\n\tpublic void setLastName(String lastName) {\n\t\tthis.lastName = lastName;\n\t}\n}\n<\/pre>\n<p>The <code>Person<\/code> class comes with two attributes to store the name of a person (<code>firstName<\/code> and <code>lastName<\/code>). The field <code>id<\/code> is used to store the object&#8217;s unique identifier as a long value. In this tutorial we are going to use mapping files instead of annotations, hence we specify the mapping of this class to the table <code>T_PERSON<\/code> as follows:<\/p>\n<pre class=\"brush:xml\">&lt;?xml version=\"1.0\"?&gt;\n&lt;!DOCTYPE hibernate-mapping PUBLIC\n        \"-\/\/Hibernate\/Hibernate Mapping DTD 3.0\/\/EN\"\n        \"http:\/\/www.hibernate.org\/dtd\/hibernate-mapping-3.0.dtd\"&gt;\n\n&lt;hibernate-mapping package=\"hibernate.entity\"&gt;\n     &lt;class name=\"Person\" table=\"T_PERSON\"&gt;\n        &lt;id name=\"id\" column=\"ID\"&gt;\n            &lt;generator class=\"native\"\/&gt;\n        &lt;\/id&gt;\n        &lt;property name=\"firstName\" column=\"FIRST_NAME\"\/&gt;\n        &lt;property name=\"lastName\" column=\"LAST_NAME\"\/&gt;\n      &lt;\/class&gt;\n&lt;\/hibernate-mapping&gt;\n<\/pre>\n<p>The XML element <code>hibernate-mapping<\/code> is used to define the package our entities reside in (here: <code>hibernate.entity<\/code>). Inside this element one <code>class<\/code> element is provided for each class that should be mapped to a table in the database.<\/p>\n<p>The <code>id<\/code> element specifies the name (<code>name<\/code>) of the class&#8217;s field that holds the unique identifier and the name of the column this value is stored in (<code>ID<\/code>). With its child element <code>generator<\/code> Hibernate gets to know how to create the unique identifier for each entity. Next to the value <code>native<\/code> shown above, Hibernate supports a long list of different strategies.<\/p>\n<p>The <code>native<\/code> strategy just chooses the best strategy for the used database product. Hence this strategy can be applied for different products. Other possible values are for example: <code>sequence<\/code> (uses a sequence in the database), <code>uuid<\/code> (generates a 128-bit UUID) and <code>assigned<\/code> (lets the application assign the value on its own). Beyond the pre-defined strategies it is possible to implement a custom strategy by implementing the interface <code>org.hibernate.id.IdentifierGenerator<\/code>.<\/p>\n<p>The fields <code>firstName<\/code> and <code>lastName<\/code> are mapped to the columns <code>FIRST_NAME<\/code> and <code>LAST_NAME<\/code> by using the XML element <code>property<\/code>. The attributes <code>name<\/code> and <code>column<\/code> define the field&#8217;s name in the class and the column, respectively.<\/p>\n<p>The following code shows exemplary how to store a person in the database:<\/p>\n<pre class=\"brush:java\">private void persistPerson(Session session) throws Exception {\n\ttry {\n\t\tTransaction transaction = session.getTransaction();\n\t\ttransaction.begin();\n\t\tPerson person = new Person();\n\t\tperson.setFirstName(\"Homer\");\n\t\tperson.setLastName(\"Simpson\");\n\t\tsession.save(person);\n\t\ttransaction.commit();\n\t} catch (Exception e) {\n\t\tif (session.getTransaction().isActive()) {\n\t\t\tsession.getTransaction().rollback();\n\t\t}\n\t\tthrow e;\n\t}\n}\n<\/pre>\n<p>Next to the code to handle the transaction it creates a new instance of the class <code>Person<\/code> and assigns two values to the fields <code>firstName<\/code> and <code>lastName<\/code>. Finally it stores the person in the database by invoking the session&#8217;s method <code>save()<\/code>.<\/p>\n<p>When we execute the code above, the following SQL statements are printed on the console:<\/p>\n<pre class=\"brush:sql\">Hibernate: \n    drop table T_PERSON if exists\nHibernate: \n    create table T_PERSON (\n        ID bigint generated by default as identity,\n        FIRST_NAME varchar(255),\n        LAST_NAME varchar(255),\n        primary key (ID)\n    )\nHibernate: \n    insert \n    into\n        T_PERSON\n        (ID, firstName, lastName, ID_ID_CARD) \n    values\n        (null, ?, ?, ?)\n<\/pre>\n<p>As we have chosen to let Hibernate drop and create the tables on startup, the first statements printed out are the <code>drop table<\/code> and <code>create table<\/code> statements. We can also see the three columns <code>ID<\/code>, <code>FIRST_NAME<\/code> and <code>LAST_NAME<\/code> of the table <code>T_PERSON<\/code> as well as the definition of the primary key (here: <code>ID<\/code>).<\/p>\n<p>After the table has been created, the invocation of <code>session.save()<\/code> issues an <code>insert<\/code> statement to the database. As Hibernate internally uses a <code>PreparedStatement<\/code>, we do not see the values on the console. In case you also want to see the values that are bound to the parameters of the <code>PreparedStatement<\/code>, you can set the logging level for the logger <code>org.hibernate.type<\/code> to <code>FINEST<\/code>. This is done within a file called <code>logging.properties<\/code> with the following content (the path to the file can be given for example as a system property <code>-Djava.util.logging.config.file=src\/main\/resources\/logging.properties<\/code>):<\/p>\n<pre class=\"brush:bash\">.handlers = java.util.logging.ConsoleHandler\n.level = INFO\n\njava.util.logging.ConsoleHandler.level = ALL\njava.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter\n\norg.hibernate.SQL.level = FINEST\norg.hibernate.type.level = FINEST\n<\/pre>\n<p>Setting the logger <code>org.hibernate.SQL<\/code> has the same effect as setting the property <code>show_sql<\/code> in the Hibernate configuration file to <code>true<\/code>.<\/p>\n<p>Now you can see the following output and therewith the actual values on the console:<\/p>\n<pre class=\"brush:sql\">DEBUG: \n    insert \n    into\n        T_PERSON\n        (ID, FIRST_NAME, LAST_NAME, ID_ID_CARD) \n    values\n        (null, ?, ?, ?)\nTRACE: binding parameter [1] as [VARCHAR] - [Homer]\nTRACE: binding parameter [2] as [VARCHAR] - [Simpson]\nTRACE: binding parameter [3] as [BIGINT] - [null]\n<\/pre>\n<h2><a name=\"intheritance\"><\/a>4. Inheritance<\/h2>\n<p>An interesting feature of O\/R mapping solutions like Hibernate is the usage of inheritance. The user can chose how to map superclass and subclass to the tables of a relational database. Hibernate supports the following mapping strategies:<\/p>\n<ul>\n<li><strong>Single table per class<\/strong>: Both superclass and subclass are mapped to the same table. An additional column marks whether the row is an instance of the superclass or subclass and fields that are not present in the superclass are left empty.<\/li>\n<li><strong>Joined subclass<\/strong>: This strategy uses a separate table for each class whereas the table for the subclass only stores the fields that are not present in the superclass. To retrieve all values for an instance of the subclass, a join between the two tables has to be performed.<\/li>\n<li><strong>Table per class<\/strong>: This strategy also uses a separate table for each class but stores in the table for the subclass also the fields of the superclass. With this strategy one row in the subclass table contains all values and in order to retrieve all values no join statement is necessary.<\/li>\n<\/ul>\n<p>The approach we are going to investigate is the &#8220;Single Table per class&#8221; approach. As a subclass of person we choose the class <code>Geek<\/code>:<\/p>\n<pre class=\"brush:java\">public class Geek extends Person {\n\tprivate String favouriteProgrammingLanguage;\n\n\tpublic String getFavouriteProgrammingLanguage() {\n\t\t\treturn favouriteProgrammingLanguage;\n\t}\n\n\tpublic void setFavouriteProgrammingLanguage(String favouriteProgrammingLanguage) {\n\t\tthis.favouriteProgrammingLanguage = favouriteProgrammingLanguage;\n\t}\n}\n<\/pre>\n<p>The class extends the already known class <code>Person<\/code> and adds an additional field named <code>favouriteProgrammingLanguage<\/code>. The mapping file for this use case looks like the following one:<\/p>\n<pre class=\"brush:xml\">&lt;?xml version=\"1.0\"?&gt;\n&lt;!DOCTYPE hibernate-mapping PUBLIC\n        \"-\/\/Hibernate\/Hibernate Mapping DTD 3.0\/\/EN\"\n        \"http:\/\/www.hibernate.org\/dtd\/hibernate-mapping-3.0.dtd\"&gt;\n\n&lt;hibernate-mapping package=\"hibernate.entity\"&gt;\n   &lt;class name=\"Person\" table=\"T_PERSON\"&gt;\n       &lt;id name=\"id\" column=\"ID\"&gt;\n           &lt;generator class=\"native\"\/&gt;\n        &lt;\/id&gt;\n        &lt;discriminator column=\"PERSON_TYPE\" type=\"string\"\/&gt;\n        &lt;property name=\"firstName\" column=\"FIRST_NAME\"\/&gt;\n        &lt;property name=\"lastName\" column=\"LAST_NAME\"\/&gt;\n        &lt;subclass name=\"Geek\" extends=\"Person\"&gt;\n             &lt;property name=\"favouriteProgrammingLanguage\" column=\"FAV_PROG_LANG\"\/&gt;\n         &lt;\/subclass&gt;\n   &lt;\/class&gt;\n&lt;\/hibernate-mapping&gt;<\/pre>\n<p>The first difference is the introduction of the <code>discriminator<\/code> column. As mentioned above this column stores the information of which type the current instance is. In our case we call it <code>PERSON_TYPE<\/code> and let for better readability a string denote the actual type. Per default Hibernate takes just the class name in this case. To save storage one can also use a column of type integer.<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<p>Beyond the discriminator we have also added the <code>subclass<\/code> element that informs Hibernate about the new Java class <code>Geek<\/code> and its field <code>favouriteProgrammingLanguage<\/code> which should be mapped to the column <code>FAV_PROG_LANG<\/code>.<\/p>\n<p>The following sample codes shows how to store instances of type <code>Geek<\/code> in the database:<\/p>\n<pre class=\"brush:java\">session.getTransaction().begin();\nGeek geek = new Geek();\ngeek.setFirstName(\"Gavin\");\ngeek.setLastName(\"Coffee\");\ngeek.setFavouriteProgrammingLanguage(\"Java\");\nsession.save(geek);\ngeek = new Geek();\ngeek.setFirstName(\"Thomas\");\ngeek.setLastName(\"Micro\");\ngeek.setFavouriteProgrammingLanguage(\"C#\");\nsession.save(geek);\ngeek = new Geek();\ngeek.setFirstName(\"Christian\");\ngeek.setLastName(\"Cup\");\ngeek.setFavouriteProgrammingLanguage(\"Java\");\nsession.save(geek);\nsession.getTransaction().commit();\n<\/pre>\n<p>Executing the code shown above, leads to the following output:<\/p>\n<pre class=\"brush:sql\">Hibernate: \n    drop table T_PERSON if exists\nHibernate: \n    create table T_PERSON (\n        ID bigint generated by default as identity,\n        PERSON_TYPE varchar(255) not null,\n        FIRST_NAME varchar(255),\n        LAST_NAME varchar(255),\n        FAV_PROG_LANG varchar(255),\n        primary key (ID)\n    )\nHibernate: \n    insert \n    into\n        T_PERSON\n        (ID, FIRST_NAME, LAST_NAME, FAV_PROG_LANG, PERSON_TYPE) \n    values\n        (null, ?, ?, ?, 'hibernate.entity.Geek')\n<\/pre>\n<p>In contrast to the previous example the table <code>T_PERSON<\/code> now contains the two new columns <code>PERSON_TYPE<\/code> and <code>FAV_PROG_LANG<\/code>. The column <code>PERSON_TYPE<\/code> contains the value <code>hibernate.entity.Geek<\/code> for geeks.<\/p>\n<p>In order to investigate the content of the <code>T_PERSON<\/code> table, we can utilize the Shell application shipped within the H2 jar file:<\/p>\n<pre class=\"brush:bash\">&gt; java -cp h2-1.3.176.jar org.h2.tools.Shell -url jdbc:h2:~\/hibernate\n...\nsql&gt; select * from t_person;\nID | PERSON_TYPE             | FIRST_NAME | LAST_NAME | FAV_PROG_LANG\n1  | hibernate.entity.Person | Homer      | Simpson   | null\n2  | hibernate.entity.Geek   | Gavin      | Coffee    | Java\n3  | hibernate.entity.Geek   | Thomas     | Micro     | C#\n4  | hibernate.entity.Geek   | Christian  | Cup       | Java\n<\/pre>\n<p>As discussed above, the column <code>PERSON_TYPE<\/code> stores the type of the instance whereas the column <code>FAV_PROG_LANG<\/code> contains the value <code>null<\/code> for instances of the superclass <code>Person<\/code>.<\/p>\n<p>Changing the mapping definition in a way that it looks like the following one, Hibernate will create for the superclass and the subclass a separate table:<\/p>\n<pre class=\"brush:xml\">&lt;?xml version=\"1.0\"?&gt;\n&lt;!DOCTYPE hibernate-mapping PUBLIC\n        \"-\/\/Hibernate\/Hibernate Mapping DTD 3.0\/\/EN\"\n        \"http:\/\/www.hibernate.org\/dtd\/hibernate-mapping-3.0.dtd\"&gt;\n\n&lt;hibernate-mapping package=\"hibernate.entity\"&gt;\n    &lt;class name=\"Person\" table=\"T_PERSON\"&gt;\n        &lt;id name=\"id\" column=\"ID\"&gt;\n            &lt;generator class=\"native\"\/&gt;\n        &lt;\/id&gt;\n        &lt;property name=\"firstName\" column=\"FIRST_NAME\"\/&gt;\n        &lt;property name=\"lastName\" column=\"LAST_NAME\"\/&gt;\n        &lt;joined-subclass name=\"Geek\" table=\"T_GEEK\"&gt;\n             &lt;key column=\"ID_PERSON\"\/&gt;\n              &lt;property name=\"favouriteProgrammingLanguage\" column=\"FAV_PROG_LANG\"\/&gt;\n         &lt;\/joined-subclass&gt;\n     &lt;\/class&gt;\n&lt;\/hibernate-mapping&gt;<\/pre>\n<p>The XML element <code>joined-subclass<\/code> tells Hibernate to create the table <code>T_GEEK<\/code> for the subclass <code>Geek<\/code> with the additional column <code>ID_PERSON<\/code>. This additional key column stores a foreign key to the table <code>T_PERSON<\/code> in order to assign each row in <code>T_GEEK<\/code> to its parent row in <code>T_PERSON<\/code>.<\/p>\n<p>Using the Java code shown above to store a few geeks in the database, results in the following output on the console:<\/p>\n<pre class=\"brush:sql\">Hibernate: \n    drop table T_GEEK if exists\nHibernate: \n    drop table T_PERSON if exists\nHibernate: \n    create table T_GEEK (\n        ID_PERSON bigint not null,\n        FAV_PROG_LANG varchar(255),\n        primary key (ID_PERSON)\n    )\nHibernate: \n    create table T_PERSON (\n        ID bigint generated by default as identity,\n        FIRST_NAME varchar(255),\n        LAST_NAME varchar(255),\n        primary key (ID)\n    )\nHibernate: \n    alter table T_GEEK \n        add constraint FK_p2ile8qooftvytnxnqtjkrbsa \n        foreign key (ID_PERSON) \n        references T_PERSON\n<\/pre>\n<p>Now Hibernate creates two tables instead of one and defines a foreign key for the table <code>T_GEEK<\/code> that references the table <code>T_PERSON<\/code>. The table <code>T_GEEK<\/code> consists of two columns: <code>ID_PERSON<\/code> to reference the corresponding person and <code>FAV_PROG_LANG<\/code> to store the favorite programming language.<\/p>\n<p>Storing a geek in the database now consists of two insert statements:<\/p>\n<pre class=\"brush:sql\">Hibernate: \n    insert \n    into\n        T_PERSON\n        (ID, FIRST_NAME, LAST_NAME, ID_ID_CARD) \n    values\n        (null, ?, ?, ?)\nHibernate: \n    insert \n    into\n        T_GEEK\n        (FAV_PROG_LANG, ID_PERSON) \n    values\n        (?, ?)\n<\/pre>\n<p>The first statement inserts a new row into the table <code>T_PERSON<\/code>, while the second one inserts a new row into the table <code>T_GEEK<\/code>. The content of these two tables look afterwards like this:<\/p>\n<pre class=\"brush:bash\">sql&gt; select * from t_person;\nID | FIRST_NAME | LAST_NAME\n1  | Homer      | Simpson  \n2  | Gavin      | Coffee   \n3  | Thomas     | Micro    \n4  | Christian  | Cup      \n\nsql&gt; select * from t_geek;\nID_PERSON | FAV_PROG_LANG\n2         | Java\n3         | C#\n4         | Java\n<\/pre>\n<p>Obviously the table <code>T_PERSON<\/code> only stores the attributes of the superclass whereas the table <code>T_GEEK<\/code> only stores the field values for the subclass. The column <code>ID_PERSON<\/code> references the corresponding row from the parent table.<\/p>\n<p>The next strategy under investigation is &#8220;table per class&#8221;. Similar to the last strategy this one also creates a separate table for each class, but in contrast the table for the subclass contains also all columns of the superclass. Therewith one row in such a table contains all values to construct an instance of this type without the need to join additional data from the parent table. On huge data set this can improve the performance of queries as joins need to find additionally the corresponding rows in the parent table. This additional lookup costs time that is circumvented with this approach.<\/p>\n<p>To use this strategy for the above use case, the mapping file can be rewritten like the following one:<\/p>\n<pre class=\"brush:xml\">&lt;?xml version=\"1.0\"?&gt;\n&lt;!DOCTYPE hibernate-mapping PUBLIC\n        \"-\/\/Hibernate\/Hibernate Mapping DTD 3.0\/\/EN\"\n        \"http:\/\/www.hibernate.org\/dtd\/hibernate-mapping-3.0.dtd\"&gt;\n\n&lt;hibernate-mapping package=\"hibernate.entity\"&gt;\n     &lt;class name=\"Person\" table=\"T_PERSON\"&gt;\n         &lt;id name=\"id\" column=\"ID\"&gt;\n             &lt;generator class=\"sequence\"\/&gt;\n         &lt;\/id&gt;\n         &lt;property name=\"firstName\" column=\"FIRST_NAME\"\/&gt;\n         &lt;property name=\"lastName\" column=\"LAST_NAME\"\/&gt;\n         &lt;union-subclass name=\"Geek\" table=\"T_GEEK\"&gt;\n              &lt;property name=\"favouriteProgrammingLanguage\" column=\"FAV_PROG_LANG\"\/&gt;\n         &lt;\/union-subclass&gt;\n\n      &lt;\/class&gt;\n&lt;\/hibernate-mapping&gt;<\/pre>\n<p>The XML element <code>union-subclass<\/code> provides the name of the entity (<code>Geek<\/code>) as well as the name of the separate table (<code>T_GEEK<\/code>) as attributes. As within the other approaches, the field <code>favouriteProgrammingLanguage<\/code> is declared as a property of the subclass.<\/p>\n<p>Another important change with regard to the other approaches is contained in the line that defines the id generator. As the other approaches use a <code>native<\/code> generator, which falls back on H2 to an identity column, this approach requires an id generator that creates identities that are unique for both tables (<code>T_PERSON<\/code> and <code>T_GEEK<\/code>).<\/p>\n<p>The identity column is just a special type of column that automatically creates for each row a new id. But with two tables we have also two identity columns and therewith the ids in the <code>T_PERSON<\/code> table can be the same as in the <code>T_GEEK<\/code> table. This conflicts with the requirement that an entity of type <code>Geek<\/code> can be created just by reading one row of the table <code>T_GEEK<\/code> and that the identifiers for all persons and geeks are unique. Therefore we are using a sequence instead of an identity column by switching the value for the <code>class<\/code> attribute from <code>native<\/code> to <code>sequence<\/code>.<\/p>\n<p>Now the DDL statements created by Hibernate look like the following ones:<\/p>\n<pre class=\"brush:sql\">Hibernate: \n    drop table T_GEEK if exists\nHibernate: \n    drop table T_PERSON if exists\nHibernate: \n    drop sequence if exists hibernate_sequence\nHibernate: \n    create table T_GEEK (\n        ID bigint not null,\n        FIRST_NAME varchar(255),\n        LAST_NAME varchar(255),\n        FAV_PROG_LANG varchar(255),\n        primary key (ID)\n    )\nHibernate: \n    create table T_PERSON (\n        ID bigint not null,\n        FIRST_NAME varchar(255),\n        LAST_NAME varchar(255),\n        primary key (ID)\n    )\nHibernate: \n    create sequence hibernate_sequence\n<\/pre>\n<p>The output above clearly demonstrates that the table <code>T_GEEK<\/code> now contains next to <code>FAV_PROG_LANG<\/code> also the columns for the superclass (<code>FIRST_NAME<\/code> and <code>LAST_NAME<\/code>). The statements do not create a foreign key between the two tables. Please also note that now the column <code>ID<\/code> is no longer an identity column but that instead a sequence is created.<\/p>\n<p>The insertion of a person and a geek issues the following statements to the database:<\/p>\n<pre class=\"brush:sql\">Hibernate: \n    call next value for hibernate_sequence\nHibernate: \n    insert \n    into\n        T_PERSON\n        (FIRST_NAME, LAST_NAME, ID) \n    values\n        (?, ?, ?, ?)\nHibernate: \n    call next value for hibernate_sequence\nHibernate: \n    insert \n    into\n        T_GEEK\n        (FIRST_NAME, LAST_NAME, FAV_PROG_LANG, ID) \n    values\n        (?, ?, ?, ?, ?)\n<\/pre>\n<p>For one person and one geek we have obviously only two insert statements. The table <code>T_GEEK<\/code> is completely filled by one insertion and contains all values of an instance of <code>Geek<\/code>:<\/p>\n<pre class=\"brush:bash\">sql&gt; select * from t_person;\nID | FIRST_NAME | LAST_NAME \n1  | Homer      | Simpson   \n\nsql&gt; select * from t_geek;\nID | FIRST_NAME | LAST_NAME | FAV_PROG_LANG\n3  | Gavin      | Coffee    | Java\n4  | Thomas     | Micro     | C#\n5  | Christian  | Cup       | Java\n<\/pre>\n<h2><a name=\"relationships\"><\/a>5. Relationships<\/h2>\n<p>Up to now the only relationship between two tables we have seen was the &#8220;extends&#8221; one. Next to the mere inheritance Hibernate can also map relationships that are based on lists where the one entity has a list of instances of another entity. The following types of relationships are distinguished:<\/p>\n<ul>\n<li><strong>One to one<\/strong>: This denotes a simple relationship in which one entity of type A belongs exactly to one entity of type B.<\/li>\n<li><strong>Many to one<\/strong>: As the name indicates, this relationship encompasses the case that an entity of type A has many child entities of type B.<\/li>\n<li><strong>Many to many<\/strong>: In this case there can be many entities of type A that belong to many entities of type B.<\/li>\n<\/ul>\n<p>To understand these different types of relationships a little better, we will investigate them in the following.<\/p>\n<h2><a name=\"relationships_onetoone\"><\/a>5.1. OneToOne<\/h2>\n<p>As an example for the &#8220;one to one&#8221; case we add the following class to our entity model:<\/p>\n<pre class=\"brush:java\">public class IdCard {\n\tprivate Long id;\n\tprivate String idNumber;\n\tprivate Date issueDate;\n\tprivate boolean valid;\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getIdNumber() {\n\t\treturn idNumber;\n\t}\n\n\tpublic void setIdNumber(String idNumber) {\n\t\tthis.idNumber = idNumber;\n\t}\n\n\tpublic Date getIssueDate() {\n\t\treturn issueDate;\n\t}\n\n\tpublic void setIssueDate(Date issueDate) {\n\t\tthis.issueDate = issueDate;\n\t}\n\n\tpublic boolean isValid() {\n\t\treturn valid;\n\t}\n\n\tpublic void setValid(boolean valid) {\n\t\tthis.valid = valid;\n\t}\n}\n<\/pre>\n<p>An identity card as an internal unique identifier as well as an external idNumber, an issue date and a boolean flag that indicates if the card is valid or not.<\/p>\n<p>On the other side of the relation the person gets a new field named <code>idCard<\/code> that references the card of this person:<\/p>\n<pre class=\"brush:java\">public class Person {\n\t...\n\tprivate IdCard idCard;\n\t\n\t...\n\t\n\tpublic IdCard getIdCard() {\n\t\treturn idCard;\n\t}\n\n\tpublic void setIdCard(IdCard idCard) {\n\t\tthis.idCard = idCard;\n\t}\n<\/pre>\n<p>To map this relation using the Hibernate specific mapping file, we change it in the following way:<\/p>\n<pre class=\"brush:xml\">    \n &lt;hibernate-mapping package=\"hibernate.entity\"&gt;\n     &lt;class name=\"IdCard\" table=\"T_ID_CARD\"&gt;\n         &lt;id name=\"id\" column=\"ID\"&gt;\n             &lt;generator class=\"sequence\"\/&gt;\n         &lt;\/id&gt;\n      &lt;\/class&gt;\n      &lt;class name=\"Person\" table=\"T_PERSON\"&gt;\n          &lt;id name=\"id\" column=\"ID\"&gt;\n              &lt;generator class=\"sequence\"\/&gt;\n          &lt;\/id&gt;\n          &lt;property name=\"firstName\" column=\"FIRST_NAME\"\/&gt;\n          &lt;property name=\"lastName\" column=\"LAST_NAME\"\/&gt;\n          &lt;many-to-one name=\"idCard\" column=\"ID_ID_CARD\" unique=\"true\"\/&gt;\n          &lt;union-subclass name=\"Geek\" table=\"T_GEEK\"&gt;\n               &lt;property name=\"favouriteProgrammingLanguage\" column=\"FAV_PROG_LANG\"\/&gt;\n          &lt;\/union-subclass&gt;\n        &lt;\/class&gt;\n&lt;\/hibernate-mapping&gt;<\/pre>\n<p>First of all we add a new <code>class<\/code> element for the new class, specifying the name of the class and its corresponding table name (here: <code>T_ID_CARD<\/code>). The field <code>id<\/code> becomes the unique identifier and should be filled with the value of a sequence.<\/p>\n<p>On the other hand the <code>Person<\/code> mapping now contains the new XML element <code>many-to-one<\/code> and references with its attribute <code>name<\/code> the field of the class <code>Person<\/code> that stores the reference to the <code>IdCard<\/code>. The optional attribute <code>column<\/code> lets us specify the exact name of the foreign key column in the table <code>T_PERSON<\/code> that links to the person&#8217;s id card. As this relation should be of type &#8220;one to one&#8221; we have to set the attribute <code>unique<\/code> to <code>true<\/code>.<\/p>\n<p>Executing this configuration results in the following DDL statements (please note that in order to reduce the number of tables we have switched back to the &#8220;single table per class&#8221; approach where we have only one table for superclass and subclass):<\/p>\n<pre class=\"brush:sql\">Hibernate: \n    drop table T_ID_CARD if exists\nHibernate: \n    drop table T_PERSON if exists\nHibernate: \n    drop sequence if exists hibernate_sequence\nHibernate: \n    create table T_ID_CARD (\n        ID bigint not null,\n        ID_NUMBER varchar(255),\n        ISSUE_DATE timestamp,\n        VALID boolean,\n        primary key (ID)\n    )\nHibernate: \n    create table T_PERSON (\n        ID bigint not null,\n        PERSON_TYPE varchar(255) not null,\n        FIRST_NAME varchar(255),\n        LAST_NAME varchar(255),\n        ID_ID_CARD bigint,\n        FAV_PROG_LANG varchar(255),\n        primary key (ID)\n    )\nHibernate: \n    alter table T_PERSON \n        add constraint UK_96axqtck4kc0be4ancejxtu0p  unique (ID_ID_CARD)\nHibernate: \n    alter table T_PERSON \n        add constraint FK_96axqtck4kc0be4ancejxtu0p \n        foreign key (ID_ID_CARD) \n        references T_ID_CARD\nHibernate: \n    create sequence hibernate_sequence\n<\/pre>\n<p>What has changed with regard to the previous examples is that the table <code>T_PERSON<\/code> now contains an additional column <code>ID_ID_CARD<\/code> that is defined as foreign key to the table <code>T_ID_CARD<\/code>. The table <code>T_ID_CARD<\/code> itself contains as expected the three columns <code>ID_NUMBER<\/code>, <code>ISSUE_DATE<\/code> and <code>VALID<\/code>.<\/p>\n<p>The Java code to insert a person together with its id card looks like the following one:<\/p>\n<pre class=\"brush:java\">Person person = new Person();\nperson.setFirstName(\"Homer\");\nperson.setLastName(\"Simpson\");\nsession.save(person);\nIdCard idCard = new IdCard();\nidCard.setIdNumber(\"4711\");\nidCard.setIssueDate(new Date());\nperson.setIdCard(idCard);\nsession.save(idCard);\n<\/pre>\n<p>Creating an instance of <code>IdCard<\/code> is straight-forward, please also note that the reference from <code>Person<\/code> to <code>IdCard<\/code> is set in the last but one line. Both instances are passed to Hibernate&#8217;s <code>save()<\/code> method.<\/p>\n<p>Looking at the code above in more detail, one might argue why we have to pass both instances to the <code>save()<\/code> method of the session. This point is justified, as Hibernate allows to define that certain operation should be &#8220;cascaded&#8221; when processing a complete entity graph. To enable cascading for the relationship to the <code>IdCard<\/code> we can simply add the attribute <code>cascade<\/code> to the <code>many-to-one<\/code> element in the mapping file:<\/p>\n<pre class=\"brush:xml\">&lt;many-to-one name=\"idCard\" column=\"ID_ID_CARD\" unique=\"true\" cascade=\"all\"\/&gt;\n<\/pre>\n<p>Using the value <code>all<\/code> tells Hibernate to cascade all types of operations. As this is not always the preferred way to handle relationships between entities, one can also select only specific operations:<\/p>\n<pre class=\"brush:xml\">&lt;many-to-one name=\"idCard\" column=\"ID_ID_CARD\" unique=\"true\" cascade=\"save-update,refresh\"\/ ?-\n&gt;\n<\/pre>\n<p>The example above demonstrates how to configure the mapping such that only calls to <code>save()<\/code>, <code>saveOrUpdate()<\/code> and <code>refresh<\/code> (re-reads the state of the given object from the database) are cascaded. Calls to the Hibernate methods <code>delete()<\/code> or <code>lock()<\/code> would for example not be forwarded.<\/p>\n<p>Using on of the two configurations above, the code to store a person together with its id card can be rewritten to the following one:<\/p>\n<pre class=\"brush:java\">Person person = new Person();\nperson.setFirstName(\"Homer\");\nperson.setLastName(\"Simpson\");\nIdCard idCard = new IdCard();\nidCard.setIdNumber(\"4711\");\nidCard.setIssueDate(new Date());\nperson.setIdCard(idCard);\nsession.save(person);\n<\/pre>\n<p>Instead of using the method <code>save()<\/code> one could also use in this use case the method <code>saveOrUpdate()<\/code>. The purpose of the method <code>saveOrUpdate()<\/code> is that it can be also used to update an existing entity. A subtle difference between both implementations is the fact that the <code>save()<\/code> methods returns the created identifier of the new entity:<\/p>\n<pre class=\"brush:java\">Long personId = (Long) session.save(person);\n<\/pre>\n<p>This is helpful when writing for example server side code that should return this identifier to the caller of the method. On the other hand the method <code>update()<\/code> does not return the identifier as it assumes that the entity has already been stored to the data store and therefore must have an identifier. Trying to update an entity without an identifier will throw an exception:<\/p>\n<pre class=\"brush:java\">org.hibernate.TransientObjectException: The given object has a null identifier: ...\n<\/pre>\n<p>Therefore <code>saveOrUpdate()<\/code> helps in cases where one wants to omit code that decides whether the entity has already been stored or not.<\/p>\n<h2><a name=\"relationships_onetoone\"><\/a>5.2. OneToMany<\/h2>\n<p>Another relation that appears frequently during O\/R mappings is the \u201cone to many\u201d relation. In this case a set of entities belongs to one entity of another type. In order to model such a relation we add the class <code>Phone<\/code> to our model:<\/p>\n<pre class=\"brush:java\">public class Phone {\n\tprivate Long id;\n\tprivate String number;\n\tprivate Person person;\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getNumber() {\n\t\treturn number;\n\t}\n\n\tpublic void setNumber(String number) {\n\t\tthis.number = number;\n\t}\n\n\tpublic Person getPerson() {\n\t\treturn person;\n\t}\n\n\tpublic void setPerson(Person person) {\n\t\tthis.person = person;\n\t}\n}\n<\/pre>\n<p>As usual the entity <code>Phone<\/code> has an internal identifier (<code>id<\/code>) and a field to store the actual phone number. The field <code>person<\/code> stores a reference back to the person who owns this phone. As one person can have more than one phone, we add a <code>Set<\/code> to the <code>Person<\/code> class that collects all phones of one person:<\/p>\n<pre class=\"brush:java\">public class Person {\n\t...\n\tprivate Set phones = new HashSet();\n\t...\n\tpublic Set getPhones() {\n\t\treturn phones;\n\t}\n\n\tpublic void setPhones(Set phones) {\n\t\tthis.phones = phones;\n\t}\n}\n<\/pre>\n<p>The mapping file has to be updated accordingly:<\/p>\n<pre class=\"brush:xml\">&lt;hibernate-mapping package=\"hibernate.entity\"&gt;\n        ...\n    &lt;class name=\"Phone\" table=\"T_PHONE\"&gt;\n        &lt;id name=\"id\" column=\"ID\"&gt;\n            &lt;generator class=\"sequence\"\/&gt;\n         &lt;\/id&gt;\n         &lt;property name=\"number\" column=\"NUMBER\"\/&gt;\n         &lt;many-to-one name=\"person\" column=\"ID_PERSON\" unique=\"false\" cascade=\"all\"\/&gt;\n     &lt;\/class&gt;\n     &lt;class name=\"Person\" table=\"T_PERSON\"&gt;\n          &lt;id name=\"id\" column=\"ID\"&gt;\n              &lt;generator class=\"sequence\"\/&gt;\n          &lt;\/id&gt;\n          &lt;discriminator column=\"PERSON_TYPE\" type=\"string\"\/&gt;\n          &lt;property name=\"firstName\" column=\"FIRST_NAME\"\/&gt;\n          &lt;property name=\"lastName\" column=\"LAST_NAME\"\/&gt;\n          &lt;many-to-one name=\"idCard\" column=\"ID_ID_CARD\" unique=\"true\" cascade=\"all\"\/&gt;\n                   &lt;subclass name=\"Geek\" extends=\"Person\"&gt;\n                &lt;property name=\"favouriteProgrammingLanguage\" column=\"FAV_PROG_LANG\"\/&gt;\n           &lt;\/subclass&gt;\n       &lt;\/class&gt;\n&lt;\/hibernate-mapping&gt;<\/pre>\n<p>The listing above shows the definition of the mapping for the class <code>Phone<\/code>. Next to the usual identifier (<code>id<\/code>) that is generated using a sequence and the field <code>number<\/code> this definition also contains out the <code>many-to-one<\/code> element. In contrast to the &#8220;one to one&#8221; relation we have seen before, the attribute <code>unique<\/code> is set to <code>false<\/code>. Beyond that the attribute <code>column<\/code> defines the name of the foreign key column and the value of the attribute <code>cascade<\/code> how Hibernate should cascade operations on this relation.<\/p>\n<p>Having executed the above configuration will print out the following DDL statements:<\/p>\n<pre class=\"brush:sql\">...\nHibernate: \n    drop table T_PERSON if exists\nHibernate: \n    drop table T_PHONE if exists\n...\nHibernate: \n    create table T_PERSON (\n        ID bigint not null,\n        PERSON_TYPE varchar(255) not null,\n        FIRST_NAME varchar(255),\n        LAST_NAME varchar(255),\n        ID_ID_CARD bigint,\n        FAV_PROG_LANG varchar(255),\n        primary key (ID)\n    )\nHibernate: \n    create table T_PHONE (\n        ID bigint not null,\n        NUMBER varchar(255),\n        ID_PERSON bigint,\n        primary key (ID)\n    )\n...\nHibernate: \n    alter table T_PHONE \n        add constraint FK_dvxwd55q1bax99ibyw4oxa8iy \n        foreign key (ID_PERSON) \n        references T_PERSON\n...\n<\/pre>\n<p>Next to the table <code>T_PERSON<\/code> Hibernate now also creates the new table <code>T_PHONE<\/code> with its three columns <code>ID<\/code>, <code>NUMBER<\/code> and <code>ID_PERSON<\/code>. As the latter column stores the reference to the <code>Person<\/code>, Hibernate also adds a foreign key constraint to the table <code>T_PHONE<\/code> that points to the column <code>ID<\/code> of the table <code>T_PERSON<\/code>.<\/p>\n<p>In order to add a phone number to one of the existing persons, we first load a specific person and then add the phone:<\/p>\n<pre class=\"brush:java\">session.getTransaction().begin();\nList resultList = session.createQuery(\"from Person as person where person.firstName = ?\").setString(0, \"Homer\").list();\nfor (Person person : resultList) {\n\tPhone phone = new Phone();\n\tphone.setNumber(\"+49 1234 456789\");\n\tsession.persist(phone);\n\tperson.getPhones().add(phone);\n\tphone.setPerson(person);\n}\nsession.getTransaction().commit();\n<\/pre>\n<p>This example shows how to load a person from the data store by using Hibernate&#8217;s Query Language (HQL). Similarly to SQL this query consists of a from and a where clause. The column <code>FIRST_NAME<\/code> is not referenced by using its SQL name. Instead the name of the Java field\/property is used. Parameters like the first name can be passed into the query by using the <code>setString()<\/code> method.<\/p>\n<p>In the following the code iterates over the found persons (should be only one) and creates a new instance of <code>Phone<\/code> that is added to the set of phones of the found person. The link back from the phone to the person is also set before the transaction is committed. Having executed this code, the database looks like the following one:<\/p>\n<pre class=\"brush:sql\">sql&gt; select * from t_person where first_name = 'Homer';\nID | PERSON_TYPE             | FIRST_NAME | LAST_NAME | ID_ID_CARD | FAV_PROG_LANG\n1  | hibernate.entity.Person | Homer      | Simpson   | 2          | null\n\nsql&gt; select * from t_phone;\nID | NUMBER          | ID_PERSON\n6  | +49 1234 456789 | 1\n<\/pre>\n<p>The result sets of the two select statements above shows that the row in <code>T_PHONE<\/code> is connected to the selected row in <code>T_PERSON<\/code> as it contains the id of the person with first name &#8220;Homer&#8221; in its column <code>ID_ID_PERSON<\/code>.<br \/>\n[ulp id=&#8217;EelW6SUHCPfAItu8&#8242;]<br \/>\n&nbsp;<\/p>\n<h2><a name=\"relationships_manytomany\"><\/a>5.3. ManyToMany<\/h2>\n<p>The next interesting relationship to look at is the &#8220;many to many&#8221; relation. In this case many entities of type A can belong to many entities of type B and vice versa. In practice this is for example the case with geeks and projects. One geek can work in multiple projects (either simultaneously or sequentially) and one project can consist of more than one geek. Therefore the new entity <code>Project<\/code> is introduced:<\/p>\n<pre class=\"brush:java\">public class Project {\n\tprivate Long id;\n\tprivate String title;\n\tprivate Set geeks = new HashSet();\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getTitle() {\n\t\treturn title;\n\t}\n\n\tpublic void setTitle(String title) {\n\t\tthis.title = title;\n\t}\n\n\tpublic Set getGeeks() {\n\t\treturn geeks;\n\t}\n\n\tpublic void setGeeks(Set geeks) {\n\t\tthis.geeks = geeks;\n\t}\n}\n<\/pre>\n<p>It consists next to the identifier (<code>id<\/code>) of a title and a set of geeks. On the other side of the relation the class <code>Geek<\/code> has a set of projects:<\/p>\n<pre class=\"brush:java\">public class Geek extends Person {\n\tprivate String favouriteProgrammingLanguage;\n\tprivate Set projects = new HashSet();\n\n\tpublic String getFavouriteProgrammingLanguage() {\n\t\t\treturn favouriteProgrammingLanguage;\n\t}\n\n\tpublic void setFavouriteProgrammingLanguage(String favouriteProgrammingLanguage) {\n\t\tthis.favouriteProgrammingLanguage = favouriteProgrammingLanguage;\n\t}\n\n\tpublic Set getProjects() {\n\t\treturn projects;\n\t}\n\n\tpublic void setProjects(Set projects) {\n\t\tthis.projects = projects;\n\t}\n}\n<\/pre>\n<p>To support this kind of relation the mapping file has to be changed in the following way:<\/p>\n<pre class=\"brush:xml\">&lt;hibernate-mapping package=\"hibernate.entity\"&gt;\n       ...\n    &lt;class name=\"Project\" table=\"T_PROJECT\"&gt;\n       &lt;id name=\"id\" column=\"ID\"&gt;\n           &lt;generator class=\"sequence\"\/&gt;\n        &lt;\/id&gt;\n        &lt;property name=\"title\" column=\"TITLE\"\/&gt;\n        &lt;set name=\"geeks\" table=\"T_GEEKS_PROJECTS\"&gt;\n           &lt;key column=\"ID_PROJECT\"\/&gt;\n           &lt;many-to-many column=\"ID_GEEK\" class=\"Geek\"\/&gt;\n        &lt;\/set&gt;\n      &lt;\/class&gt;\n      &lt;class name=\"Person\" table=\"T_PERSON\"&gt;\n         &lt;id name=\"id\" column=\"ID\"&gt;\n             &lt;generator class=\"sequence\"\/&gt;\n         &lt;\/id&gt;\n         &lt;discriminator column=\"PERSON_TYPE\" type=\"string\"\/&gt;\n         &lt;property name=\"firstName\" column=\"FIRST_NAME\"\/&gt;\n         &lt;property name=\"lastName\" column=\"LAST_NAME\"\/&gt;\n         &lt;many-to-one name=\"idCard\" column=\"ID_ID_CARD\" unique=\"true\" cascade=\"all\"\/&gt;\n         &lt;subclass name=\"Geek\" extends=\"Person\"&gt;\n              &lt;property name=\"favouriteProgrammingLanguage\" column=\"FAV_PROG_LANG\"\/&gt;\n              &lt;set name=\"projects\" inverse=\"true\"&gt;\n                   &lt;key column=\"ID_GEEK\"\/&gt;\n                   &lt;many-to-many column=\"ID_PROJECT\" class=\"Project\"\/&gt;\n               &lt;\/set&gt;\n        &lt;\/subclass&gt;\n      &lt;\/class&gt;\n&lt;\/hibernate-mapping&gt;<\/pre>\n<p>First of all we see the new class <code>Project<\/code> that is mapped to the table <code>T_PROJECT<\/code>. Its unique identifier is stored in the field <code>id<\/code> and its field <code>title<\/code> is stored in the column <code>TITLE<\/code>. The XML element <code>set<\/code> defines the one side of the mapping: the items inside the set <code>geeks<\/code> should be stored in a separate table named <code>T_GEEKS_PROJECTS<\/code> with the columns <code>ID_PROJECT<\/code> and <code>ID_GEEK<\/code>. On the other side of the relation the XML element <code>set<\/code> inside the <code>subclass<\/code> for <code>Geek<\/code> defines the inverse relation (<code>inverse=\"true\"<\/code>). On this side the field in the class <code>Geek<\/code> is called <code>projects<\/code> and the reference class is <code>Project<\/code>.<\/p>\n<p>The resulting statements to create the tables look like this:<\/p>\n<pre class=\"brush:sql\">...\nHibernate: \n    drop table T_GEEKS_PROJECTS if exists\nHibernate: \n    drop table T_PROJECT if exists\n...\nHibernate: \n    create table T_GEEKS_PROJECTS (\n        ID_PROJECT bigint not null,\n        ID_GEEK bigint not null,\n        primary key (ID_PROJECT, ID_GEEK)\n    )\nHibernate: \n    create table T_PROJECT (\n        ID bigint not null,\n        TITLE varchar(255),\n        primary key (ID)\n    )\n...\nHibernate: \n    alter table T_GEEKS_PROJECTS \n        add constraint FK_2kp3f3tq46ckky02pshvjngaq \n        foreign key (ID_GEEK) \n        references T_PERSON\nHibernate: \n    alter table T_GEEKS_PROJECTS \n        add constraint FK_36tafu1nw9j5o51d21xm5rqne \n        foreign key (ID_PROJECT) \n        references T_PROJECT\n...\n<\/pre>\n<p>These statements create the new tables <code>T_PROJECT<\/code> as well as <code>T_GEEKS_PROJECTS<\/code>. The table <code>T_PROJECT<\/code> consists of the columns <code>ID<\/code> and <code>TITLE<\/code> whereby the values in the column <code>ID<\/code> are referred to in the new table <code>T_GEEKS_PROJECTS<\/code> in its column <code>ID_PROJECT<\/code>. The second foreign key on this table points to the primary key of <code>T_PERSON<\/code>.<\/p>\n<p>In order to insert a project with a few geeks that can program in Java into the data store, the following code can be used:<\/p>\n<pre class=\"brush:java\">session.getTransaction().begin();\nList resultList = session.createQuery(\"from Geek as geek \n\twhere geek.favouriteProgrammingLanguage = ?\").setString(0, \"Java\").list();\nProject project = new Project();\nproject.setTitle(\"Java Project\");\nfor (Geek geek : resultList) {\n\tproject.getGeeks().add(geek);\n\tgeek.getProjects().add(project);\n}\nsession.save(project);\nsession.getTransaction().commit();\n<\/pre>\n<p>The initial query selects all geeks that have &#8220;Java&#8221; as their favorite programming language. Then a new instance of <code>Project<\/code> is created and all geeks that are in the result set of the query are added to the project&#8217;s set of geeks. On the other side of the relation the project is added to the set of projects for the geek. Finally the project is stored and the transaction gets committed.<\/p>\n<p>After having executed this code, the database looks like the following:<\/p>\n<pre class=\"brush:bash\">sql&gt; select * from t_person;\nID | PERSON_TYPE             | FIRST_NAME | LAST_NAME | ID_ID_CARD | FAV_PROG_LANG\n1  | hibernate.entity.Person | Homer      | Simpson   | 2          | null\n3  | hibernate.entity.Geek   | Gavin      | Coffee    | null       | Java\n4  | hibernate.entity.Geek   | Thomas     | Micro     | null       | C#\n5  | hibernate.entity.Geek   | Christian  | Cup       | null       | Java\n\nsql&gt; select * from t_project;\nID | TITLE\n7  | Java Project\n\nsql&gt; select * from t_geeks_projects;\nID_PROJECT | ID_GEEK\n7          | 5\n7          | 3\n<\/pre>\n<p>The first select reveals that only the two geeks with id 3 and 5 have denoted that Java is their favorite programming language. Hence the project with title &#8220;Java Project&#8221; (id: 7) consist of the two geeks with ids 3 and 5 (last select statement).<\/p>\n<h2><a name=\"relationships_components\"><\/a>5.4. Component<\/h2>\n<p>Object-Oriented design rules suggest to extract commonly used fields to a separate class. The <code>Project<\/code> class above for example misses still a start and end date. But as such a period of time can be used for other entities as well, we can create a new class called <code>Period<\/code> that encapsulates the two fields <code>startDate<\/code> and <code>endDate<\/code>:<\/p>\n<pre class=\"brush:java\">public class Period {\n\tprivate Date startDate;\n\tprivate Date endDate;\n\n\tpublic Date getStartDate() {\n\t\treturn startDate;\n\t}\n\n\tpublic void setStartDate(Date startDate) {\n\t\tthis.startDate = startDate;\n\t}\n\n\tpublic Date getEndDate() {\n\t\treturn endDate;\n\t}\n\n\tpublic void setEndDate(Date endDate) {\n\t\tthis.endDate = endDate;\n\t}\n}\n\npublic class Project {\n\t...\n\tprivate Period period;\n\t...\n\tpublic Period getPeriod() {\n\t\treturn period;\n\t}\n\n\tpublic void setPeriod(Period period) {\n\t\tthis.period = period;\n\t}\n}\n<\/pre>\n<p>But we do not want that Hibernate creates a separate table for the period as each <code>Project<\/code> should only have exactly one start and end date and we want to circumvent the additional join. In this case Hibernate can map the two fields in the embedded class <code>Period<\/code> to the same table as the class <code>Project<\/code>:<\/p>\n<pre class=\"brush:xml\">    \n&lt;hibernate-mapping package=\"hibernate.entity\"&gt;\n      ...\n      &lt;class name=\"Project\" table=\"T_PROJECT\"&gt;\n          &lt;id name=\"id\" column=\"ID\"&gt;\n                &lt;generator class=\"sequence\"\/&gt;\n          &lt;\/id&gt;\n          &lt;property name=\"title\" column=\"TITLE\"\/&gt;\n          &lt;set name=\"geeks\" table=\"T_GEEKS_PROJECTS\"&gt;\n                 &lt;key column=\"ID_PROJECT\"\/&gt;\n                 &lt;many-to-many column=\"ID_GEEK\" class=\"Geek\"\/&gt;\n           &lt;\/set&gt;\n           &lt;component name=\"period\"&gt;\n                  &lt;property name=\"startDate\" column=\"START_DATE\"\/&gt;\n                  &lt;property name=\"endDate\" column=\"END_DATE\"\/&gt;\n           &lt;\/component&gt;\n         &lt;\/class&gt;\n         ...\n&lt;\/hibernate-mapping&gt;<\/pre>\n<p>The way how to map this embedded class to fields of the table <code>T_PROJECT<\/code> is to use the <code>component<\/code> element and provide the name of the field in the <code>Project<\/code> class for the <code>name<\/code> attribute. The two fields of the class <code>Period<\/code> are then just declared as properties of the <code>component<\/code>.<\/p>\n<p>This results in the following DDL statement:<\/p>\n<pre class=\"brush:sql\">...\nHibernate: \n    create table T_PROJECT (\n        ID bigint not null,\n        TITLE varchar(255),\n        START_DATE timestamp,\n        END_DATE timestamp,\n        primary key (ID)\n    )\n...\n<\/pre>\n<p>Although the fields for <code>START_DATE<\/code> and <code>END_DATE<\/code> are located in a separate class, Hibernate adds them to the table <code>T_PROJECT<\/code>. The following code creates a new project and adds a period to it:<\/p>\n<pre class=\"brush:java\">Project project = new Project();\nproject.setTitle(\"Java Project\");\nPeriod period = new Period();\nperiod.setStartDate(new Date());\nproject.setPeriod(period);\n...\nsession.save(project);\n<\/pre>\n<p>This results in the following data situation:<\/p>\n<pre class=\"brush:sql\">sql&gt; select * from t_project;\nID | TITLE        | START_DATE              | END_DATE\n7  | Java Project | 2015-01-01 19:45:12.274 | null\n<\/pre>\n<p>To load the period together with the project no additional code has to be written, the period is automatically loaded and initialized:<\/p>\n<pre class=\"brush:java\">List projects = session.createQuery(\"from Project as p where p.title = ?\")\n\t.setString(0, \"Java Project\").list();\nfor (Project project : projects) {\n\tSystem.out.println(\"Project: \" + project.getTitle() + \" starts at \" + project.getPeriod().getStartDate());\n}\n<\/pre>\n<p>Just in case all fields of the period have been set to <code>NULL<\/code> in the database, Hibernate also sets the reference to <code>Period<\/code> to <code>null<\/code>.<\/p>\n<h1><a name=\"dataTypes\"><\/a>6. User-defined Data Types<\/h1>\n<p>When working for example with a legacy database it can happen that certain columns are modelled in a different way than Hibernate would map them. The <code>Boolean<\/code> data type for example is mapped on an H2 database to the type <code>boolean<\/code>. If the original development team has decided to map boolean values using a string with the value &#8220;0&#8221; and &#8220;1&#8221;, Hibernate allows to implement user-defined types that are used for the mapping.<\/p>\n<p>Hibernate defines the interface <code>org.hibernate.usertype.UserType<\/code> that has to be implemented:<\/p>\n<pre class=\"brush:java\">public interface UserType {\n    int[] sqlTypes();\n    Class returnedClass();\n    boolean equals(Object var1, Object var2) throws HibernateException;\n    int hashCode(Object var1) throws HibernateException;\n    Object nullSafeGet(ResultSet var1, String[] var2, SessionImplementor var3, Object var4) throws HibernateException, SQLException;\n    void nullSafeSet(PreparedStatement var1, Object var2, int var3, SessionImplementor var4) throws HibernateException, SQLException;\n    Object deepCopy(Object var1) throws HibernateException;\n    boolean isMutable();\n    Serializable disassemble(Object var1) throws HibernateException;\n    Object assemble(Serializable var1, Object var2) throws HibernateException;\n    Object replace(Object var1, Object var2, Object var3) throws HibernateException;\n}\n<\/pre>\n<p>Simple implementations for those methods that are not specific for our problem are shown below:<\/p>\n<pre class=\"brush:java\">@Override\npublic boolean equals(Object x, Object y) throws HibernateException {\n\tif (x == null) {\n\t\treturn y == null;\n\t} else {\n\t\treturn y != null &amp;&amp; x.equals(y);\n\t}\n}\n\n@Override\npublic int hashCode(Object o) throws HibernateException {\n\treturn o.hashCode();\n}\n\n@Override\npublic Object deepCopy(Object o) throws HibernateException {\n\treturn o;\n}\n\n@Override\npublic boolean isMutable() {\n\treturn false;\n}\n\n@Override\npublic Serializable disassemble(Object o) throws HibernateException {\n\treturn (Serializable) o;\n}\n\n@Override\npublic Object assemble(Serializable cached, Object owner) throws HibernateException {\n\treturn cached;\n}\n\n@Override\npublic Object replace(Object original, Object target, Object owner) throws HibernateException {\n\treturn original;\n}\n<\/pre>\n<p>The interesting part of the <code>UserType<\/code> are the methods <code>nullSafeGet()<\/code> and <code>nullSafeSet()<\/code>:<\/p>\n<pre class=\"brush:java\">@Override\npublic Object nullSafeGet(ResultSet resultSet, String[] strings, \n\tSessionImplementor sessionImplementor, Object o) throws HibernateException, SQLException {\n\tString str = (String) StringType.INSTANCE.nullSafeGet(resultSet, strings[0], sessionImplementor, o);\n\tif (\"1\".equals(str)) {\n\t\treturn Boolean.TRUE;\n\t}\n\treturn Boolean.FALSE;\n}\n\n@Override\npublic void nullSafeSet(PreparedStatement preparedStatement, Object value, \n\tint i, SessionImplementor sessionImplementor) throws HibernateException, SQLException {\n\tString valueToStore = \"0\";\n\tif (value != null) {\n\t\tBoolean booleanValue = (Boolean) value;\n\t\tif (booleanValue.equals(Boolean.TRUE)) {\n\t\t\tvalueToStore = \"1\";\n\t\t}\n\t}\n\tStringType.INSTANCE.nullSafeSet(preparedStatement,valueToStore, i, sessionImplementor);\n}\n<\/pre>\n<p>The method <code>nullSafeGet()<\/code> uses Hibernate&#8217;s <code>StringType<\/code> implementation to extract the string representation of the boolean value from the <code>ResultSet<\/code> of the underlying query. If the returned string equals &#8220;1&#8221; the method returns &#8220;true&#8221;, otherwise it returns &#8220;false&#8221;.<\/p>\n<p>Before an <code>insert<\/code> statement can be executed, the boolean value passed in as parameter <code>value<\/code> has to be &#8220;decoded&#8221; into either the string &#8220;1&#8221; or the string &#8220;0&#8221;. The method <code>nullSafeSet()<\/code> then uses Hibernate&#8217;s <code>StringType<\/code> implementation to set this string value on the <code>PreparedStatement<\/code>.<\/p>\n<p>Finally we have to tell Hibernate which kind of object is returned from <code>nullSafeGet()<\/code> and which type of column it should use for this type:<\/p>\n<pre class=\"brush:java\">@Override\npublic int[] sqlTypes() {\n\treturn new int[]{ Types.VARCHAR };\n}\n\n@Override\npublic Class returnedClass() {\n\treturn Boolean.class;\n}\n<\/pre>\n<p>Having implemented the <code>UserType<\/code> interface, an instance of this class can now be given to the <code>Configuration<\/code>:<\/p>\n<pre class=\"brush:java\">Configuration configuration = new Configuration();\nconfiguration.configure(\"hibernate.cfg.xml\");\nconfiguration.registerTypeOverride(new MyBooleanType(), new String[]{\"MyBooleanType\"});\n...\n<\/pre>\n<p><code>MyBooleanType<\/code> is here our implementation of the <code>UserType<\/code> interface, whereas the <code>String<\/code> array defines how to reference this type in the mapping file:<\/p>\n<pre class=\"brush:xml\">    \n&lt;hibernate-mapping package=\"hibernate.entity\"&gt;\n      &lt;class name=\"IdCard\" table=\"T_ID_CARD\"&gt;\n           &lt;id name=\"id\" column=\"ID\"&gt;\n               &lt;generator class=\"sequence\"\/&gt;\n           &lt;\/id&gt;\n           &lt;property name=\"idNumber\" column=\"ID_NUMBER\"\/&gt;\n           &lt;property name=\"issueDate\" column=\"ISSUE_DATE\"\/&gt;\n           &lt;property name=\"valid\" column=\"VALID\" type=\"MyBooleanType\"\/&gt;\n        &lt;\/class&gt;\n        ...\n&lt;\/hibernate-mapping&gt;<\/pre>\n<p>As can be seen from the snippet above, the new type &#8220;MyBooleanType&#8221; is used for the boolean property of the table <code>T_ID_CARD<\/code>:<\/p>\n<pre class=\"brush:bash\">sql&gt; select * from t_id_card;\nID | ID_NUMBER | ISSUE_DATE              | VALID\n2  | 4711      | 2015-03-27 11:49:57.533 | 1\n<\/pre>\n<h1><a name=\"interceptors\"><\/a>7. Interceptors<\/h1>\n<p>A project may come with the requirement that for each entity\/table the timestamp of its creation and its last update should be tracked. Setting these two values for each entity on all insert and update operations is a fairly tedious task. Therefore Hibernate offers the ability to implement interceptors that are called before an insert or update operation is performed. This way the code to set the creation and update timestamp can be extracted to a single place in the code base and does not have to be copied to all locations where it would be necessary.<br \/>\nAs an example we are going to implement an audit trail that tracks the creation and update of the <code>Project<\/code> entity. This can be done by extending the class <code>EmptyInterceptor<\/code>:<\/p>\n<pre class=\"brush:java\">public class AuditInterceptor extends EmptyInterceptor {\n\n\t@Override\n\tpublic boolean onSave(Object entity, Serializable id, Object[] state, \n\t\tString[] propertyNames, Type[] types) {\n\t\tif (entity instanceof Auditable) {\n\t\t\tfor ( int i=0; i &lt; propertyNames.length; i++ ) {\n\t\t\t\tif ( \"created\".equals( propertyNames[i] ) ) {\n\t\t\t\t\tstate[i] = new Date();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, \n\t\tObject[] previousState, String[] propertyNames, Type[] types) {\n\t\tif (entity instanceof Auditable) {\n\t\t\tfor ( int i=0; i &lt; propertyNames.length; i++ ) {\n\t\t\t\tif ( \"lastUpdate\".equals( propertyNames[i] ) ) {\n\t\t\t\t\tcurrentState[i] = new Date();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n}\n<\/pre>\n<p>As the class <code>EmptyInterceptor<\/code> already implements all methods defined in the interface <code>Interceptor<\/code>, we only have to override the methods <code>onSave()<\/code> and <code>onFlushDirty()<\/code>. In order to easily find all entities that have a field <code>created<\/code> and <code>lastUpdate<\/code> we extract the getter and setter methods for these entities into a separate interface called <code>Auditable<\/code>:<\/p>\n<pre class=\"brush:java\">public interface Auditable {\n\tDate getCreated();\n\tvoid setCreated(Date created);\n\tDate getLastUpdate();\n\tvoid setLastUpdate(Date lastUpdate);\n}\n<\/pre>\n<p>With this interface it is easy to check whether the instance passed into the interceptor is of type <code>Auditable<\/code>. Unfortunately we cannot modify the entity directly through the getter and setter methods but we have to use the two arrays <code>propertyNames<\/code> and <code>state<\/code>. In the array <code>propertyNames<\/code> we have to find the property <code>created<\/code> (<code>lastUpdate<\/code>) and use its index to set the corresponding element in the array <code>state<\/code> (<code>currentState<\/code>).<\/p>\n<p>Without the appropriate property definitions in the mapping file Hibernate will not create the columns in the tables. Hence the mapping file has to be updated:<\/p>\n<pre class=\"brush:xml\"> &lt;hibernate-mapping&gt;\n        ...\n    &lt;class name=\"Project\" table=\"T_PROJECT\"&gt;\n        &lt;id name=\"id\" column=\"ID\"&gt;\n            &lt;generator class=\"sequence\"\/&gt;\n        &lt;\/id&gt;\n        &lt;property name=\"title\" column=\"TITLE\"\/&gt;\n        &lt;set name=\"geeks\" table=\"T_GEEKS_PROJECTS\"&gt;\n             &lt;key column=\"ID_PROJECT\"\/&gt;\n             &lt;many-to-many column=\"ID_GEEK\" class=\"Geek\"\/&gt;\n         &lt;\/set&gt;\n         &lt;component name=\"period\"&gt;\n              &lt;property name=\"startDate\" column=\"START_DATE\"\/&gt;\n              &lt;property name=\"endDate\" column=\"END_DATE\"\/&gt;\n         &lt;\/component&gt;\n         &lt;property name=\"created\" column=\"CREATED\" type=\"timestamp\"\/&gt;\n         &lt;property name=\"lastUpdate\" column=\"LAST_UPDATE\" type=\"timestamp\"\/&gt;\n     &lt;\/class&gt;\n          ...\n&lt;\/hibernate-mapping&gt;<\/pre>\n<p>As can be seen from the snippet above, the two new properties <code>created<\/code> and <code>lastUpdate<\/code> are of type <code>timestamp<\/code>:<\/p>\n<pre class=\"brush:bash\">sql&gt; select * from t_person;\nID | PERSON_TYPE             | FIRST_NAME | LAST_NAME | CREATED                 | LAST_UPDATE | ID_ID_CARD | FAV_PROG_LANG\n1  | hibernate.entity.Person | Homer      | Simpson   | 2015-01-01 19:45:42.493 | null        | 2          | null\n3  | hibernate.entity.Geek   | Gavin      | Coffee    | 2015-01-01 19:45:42.506 | null        | null       | Java\n4  | hibernate.entity.Geek   | Thomas     | Micro     | 2015-01-01 19:45:42.507 | null        | null       | C#\n5  | hibernate.entity.Geek   | Christian  | Cup       | 2015-01-01 19:45:42.507 | null        | null       | Java\n<\/pre>\n<h1><a name=\"download\"><\/a>8. Download&nbsp;Hibernate Tutorial Source Code<\/h1>\n<p>This was a&nbsp;Hibernate Tutorial.<\/p>\n<div class=\"download\"><strong>Download<\/strong><br \/>\nYou can download the full source code of this tutorial here: <a href=\"http:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2015\/03\/hibernate-tutorial-sources.zip\"><strong>hibernate-tutorial-sources<\/strong><\/a>.<\/div>\n","protected":false},"excerpt":{"rendered":"<p>EDITORIAL NOTE: In this post, we feature a comprehensive Hibernate Tutorial. Hibernate ORM (Hibernate in short) is an object-relational mapping framework, facilitating the conversion of an object-oriented domain model to a traditional relational database. Hibernate solves the object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions. Hibernate is one &hellip;<\/p>\n","protected":false},"author":506,"featured_media":153,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[8],"tags":[31,1039],"class_list":["post-38731","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-enterprise-java","tag-jboss-hibernate","tag-ultimate"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Hibernate Tutorial \u2013 The ULTIMATE Guide (PDF Download) - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"In this ULTIMATE Hibernate tutorial all major aspects like entity manager, session factory, inheritance and more are explained to quickly get started!\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.javacodegeeks.com\/2015\/03\/hibernate-tutorial.html\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Hibernate Tutorial \u2013 The ULTIMATE Guide (PDF Download) - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"In this ULTIMATE Hibernate tutorial all major aspects like entity manager, session factory, inheritance and more are explained to quickly get started!\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.javacodegeeks.com\/2015\/03\/hibernate-tutorial.html\" \/>\n<meta property=\"og:site_name\" content=\"Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2015-03-31T07:00:15+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-12-05T13:39:07+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/jboss-hibernate-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Martin Mois\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Martin Mois\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"24 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/03\\\/hibernate-tutorial.html#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/03\\\/hibernate-tutorial.html\"},\"author\":{\"name\":\"Martin Mois\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/52c1e27ea19337c20d53df5286590760\"},\"headline\":\"Hibernate Tutorial \u2013 The ULTIMATE Guide (PDF Download)\",\"datePublished\":\"2015-03-31T07:00:15+00:00\",\"dateModified\":\"2023-12-05T13:39:07+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/03\\\/hibernate-tutorial.html\"},\"wordCount\":5260,\"commentCount\":9,\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/03\\\/hibernate-tutorial.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/jboss-hibernate-logo.jpg\",\"keywords\":[\"JBoss Hibernate\",\"Ultimate\"],\"articleSection\":[\"Enterprise Java\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/03\\\/hibernate-tutorial.html#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/03\\\/hibernate-tutorial.html\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/03\\\/hibernate-tutorial.html\",\"name\":\"Hibernate Tutorial \u2013 The ULTIMATE Guide (PDF Download) - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/03\\\/hibernate-tutorial.html#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/03\\\/hibernate-tutorial.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/jboss-hibernate-logo.jpg\",\"datePublished\":\"2015-03-31T07:00:15+00:00\",\"dateModified\":\"2023-12-05T13:39:07+00:00\",\"description\":\"In this ULTIMATE Hibernate tutorial all major aspects like entity manager, session factory, inheritance and more are explained to quickly get started!\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/03\\\/hibernate-tutorial.html#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/03\\\/hibernate-tutorial.html\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/03\\\/hibernate-tutorial.html#primaryimage\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/jboss-hibernate-logo.jpg\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/jboss-hibernate-logo.jpg\",\"width\":150,\"height\":150},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/2015\\\/03\\\/hibernate-tutorial.html#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/category\\\/java\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Enterprise Java\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/category\\\/java\\\/enterprise-java\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"Hibernate Tutorial \u2013 The ULTIMATE Guide (PDF Download)\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Developers Resource Center\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.javacodegeeks.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/javacodegeeks\",\"https:\\\/\\\/x.com\\\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/52c1e27ea19337c20d53df5286590760\",\"name\":\"Martin Mois\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/051a80ba18f758940b686c6c4bb4b5f02d59abe8cc42a95b3545f7565c7a40a1?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/051a80ba18f758940b686c6c4bb4b5f02d59abe8cc42a95b3545f7565c7a40a1?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/051a80ba18f758940b686c6c4bb4b5f02d59abe8cc42a95b3545f7565c7a40a1?s=96&d=mm&r=g\",\"caption\":\"Martin Mois\"},\"description\":\"Martin is a Java EE enthusiast and works for an international operating company. He is interested in clean code and the software craftsmanship approach. He also strongly believes in automated testing and continuous integration.\",\"sameAs\":[\"http:\\\/\\\/martinsdeveloperworld.wordpress.com\\\/\"],\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/author\\\/martin-mois\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Hibernate Tutorial \u2013 The ULTIMATE Guide (PDF Download) - Java Code Geeks","description":"In this ULTIMATE Hibernate tutorial all major aspects like entity manager, session factory, inheritance and more are explained to quickly get started!","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.javacodegeeks.com\/2015\/03\/hibernate-tutorial.html","og_locale":"en_US","og_type":"article","og_title":"Hibernate Tutorial \u2013 The ULTIMATE Guide (PDF Download) - Java Code Geeks","og_description":"In this ULTIMATE Hibernate tutorial all major aspects like entity manager, session factory, inheritance and more are explained to quickly get started!","og_url":"https:\/\/www.javacodegeeks.com\/2015\/03\/hibernate-tutorial.html","og_site_name":"Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_published_time":"2015-03-31T07:00:15+00:00","article_modified_time":"2023-12-05T13:39:07+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/jboss-hibernate-logo.jpg","type":"image\/jpeg"}],"author":"Martin Mois","twitter_card":"summary_large_image","twitter_creator":"@javacodegeeks","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Martin Mois","Est. reading time":"24 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.javacodegeeks.com\/2015\/03\/hibernate-tutorial.html#article","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/2015\/03\/hibernate-tutorial.html"},"author":{"name":"Martin Mois","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/52c1e27ea19337c20d53df5286590760"},"headline":"Hibernate Tutorial \u2013 The ULTIMATE Guide (PDF Download)","datePublished":"2015-03-31T07:00:15+00:00","dateModified":"2023-12-05T13:39:07+00:00","mainEntityOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/2015\/03\/hibernate-tutorial.html"},"wordCount":5260,"commentCount":9,"publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/2015\/03\/hibernate-tutorial.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/jboss-hibernate-logo.jpg","keywords":["JBoss Hibernate","Ultimate"],"articleSection":["Enterprise Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.javacodegeeks.com\/2015\/03\/hibernate-tutorial.html#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.javacodegeeks.com\/2015\/03\/hibernate-tutorial.html","url":"https:\/\/www.javacodegeeks.com\/2015\/03\/hibernate-tutorial.html","name":"Hibernate Tutorial \u2013 The ULTIMATE Guide (PDF Download) - Java Code Geeks","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/2015\/03\/hibernate-tutorial.html#primaryimage"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/2015\/03\/hibernate-tutorial.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/jboss-hibernate-logo.jpg","datePublished":"2015-03-31T07:00:15+00:00","dateModified":"2023-12-05T13:39:07+00:00","description":"In this ULTIMATE Hibernate tutorial all major aspects like entity manager, session factory, inheritance and more are explained to quickly get started!","breadcrumb":{"@id":"https:\/\/www.javacodegeeks.com\/2015\/03\/hibernate-tutorial.html#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.javacodegeeks.com\/2015\/03\/hibernate-tutorial.html"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/2015\/03\/hibernate-tutorial.html#primaryimage","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/jboss-hibernate-logo.jpg","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/jboss-hibernate-logo.jpg","width":150,"height":150},{"@type":"BreadcrumbList","@id":"https:\/\/www.javacodegeeks.com\/2015\/03\/hibernate-tutorial.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Java","item":"https:\/\/www.javacodegeeks.com\/category\/java"},{"@type":"ListItem","position":3,"name":"Enterprise Java","item":"https:\/\/www.javacodegeeks.com\/category\/java\/enterprise-java"},{"@type":"ListItem","position":4,"name":"Hibernate Tutorial \u2013 The ULTIMATE Guide (PDF Download)"}]},{"@type":"WebSite","@id":"https:\/\/www.javacodegeeks.com\/#website","url":"https:\/\/www.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Developers Resource Center","publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/www.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/52c1e27ea19337c20d53df5286590760","name":"Martin Mois","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/051a80ba18f758940b686c6c4bb4b5f02d59abe8cc42a95b3545f7565c7a40a1?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/051a80ba18f758940b686c6c4bb4b5f02d59abe8cc42a95b3545f7565c7a40a1?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/051a80ba18f758940b686c6c4bb4b5f02d59abe8cc42a95b3545f7565c7a40a1?s=96&d=mm&r=g","caption":"Martin Mois"},"description":"Martin is a Java EE enthusiast and works for an international operating company. He is interested in clean code and the software craftsmanship approach. He also strongly believes in automated testing and continuous integration.","sameAs":["http:\/\/martinsdeveloperworld.wordpress.com\/"],"url":"https:\/\/www.javacodegeeks.com\/author\/martin-mois"}]}},"_links":{"self":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/38731","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/users\/506"}],"replies":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=38731"}],"version-history":[{"count":0,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/38731\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media\/153"}],"wp:attachment":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=38731"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=38731"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=38731"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}