Hibernate Hello World Example

Hibernate was started in 2001 by Gavin King as an alternative to using EJB2-style entity beans. Its mission back then was to simply offer better persistence capabilities than offered by EJB2 by simplifying the complexities and allowing for missing features.

Hibernate used its mapping files and configuration files to achieve its objectives. With the introduction of annotations in java community with JDK 1.5, Hibernate community started working on Hibernate 3, which had support for annotations. The current version of hibernate is hibernate 5.

In this hibernate example with annotations, we will learn more about hibernate and step by step build our first running example application for beginners.

Table of Contents

1. What is hibernate
2. How hibernate works
3. Relation of hibernate with JPA
4. Hibernate hello world example

1. What is hibernate

Hibernate is an open source object relational mapping tool for Java. It provides a framework for mapping an object-oriented domain model to a traditional relational database. Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC.

Mapping Java classes to database tables is accomplished through the configuration of an XML file or by using Java annotations. There are facilities to arrange one-to-many and many-to-many relationships between classes are provided.

In addition to managing associations between objects, Hibernate can also manage reflexive associations where an object has a one-to-many relationship with other instances of its own type.

2. How hibernate works?

Hibernate doesn’t get in our way; nor does it force us to change the way our objects behave. The objects don’t need to implement any magical interfaces in order to be blessed with the ability to persist. All we have to do to put some meta data in form of annotations telling hibernate that how to use them when mapping them with database. At runtime, hibernate reads these annotations and use this information to build queries to send to some relational database.

There is a simple, intuitive API in Hibernate to perform queries against the objects represented by the database, to change those objects we just interact with them normally in the program, and then tell Hibernate to save the changes. Creating new objects is similarly simple; we just create them in the normal way and tell Hibernate about them using annotations so they can get stored to the database.

3. Relation of hibernate with JPA

JPA (Java Persistence API) is an specification for persistence providers to implement. Hibernate is one such implementation of JPA specification. We can annotate our classes as much as we would like with JPA annotations, however without an implementation, nothing will happen.

Think of JPA as the guidelines/specification that must be followed or an interface, while Hibernates JPA implementation is code that meets the API as defined by JPA and provides the under the hood functionality.

When we use hibernate with JPA we are actually using the Hibernate JPA implementation. The benefit of this is that we can swap out hibernates implementation of JPA for another implementation of the JPA specification.

When we use straight hibernate your locking into the implementation because other ORMs may use different methods/configurations and annotations, therefore we cannot just switch over to another ORM.

4. Hibernate hello world example

Lets create our step by step hibernate 5 hello world example. In this example, I have created an Employee class and declared four attributes id, email, firstname and lastname.

I want the id attribute should be generated automatically so that the application code does not store a local cache of employee ids.

So far we targeted what we want to make in our first application. Let’s identify the files that need to be created.

  1. hibernate.cfg.xml -This configuration file will be used to store database connection information and schema level settings.
  2. EmployeeEntity.java – This class will refer Java POJOs having hibernate annotations.
  3. HibernateUtil.java – This class will have utility methods which will be used for creating session factory and session objects.
  4. TestHibernate.java – This class will be used to test our configuration settings and Emplyee entity annotations.

Before moving into code, lets see the project setup and adding maven dependencies which need to added to pom.xml to include all compile time and runtime dependencies.

4.1. Create a maven project

Create a simple maven project.

mvn-create-java-project1-5587126

4.2. Make project to support eclipse

$ mvn eclipse:eclipse

adding-eclipse-support-7216225

3. Import java project to eclipse workspace

Import the project into eclipse.

import-in-eclipse-4531059

The above steps will create the minimum setup. Now its time to add hibernate dependencies.

4.4. Hibernate Maven Dependencies

At minimum, we will need hibernate-core dependency. We are using in-memory database H2 for this example. So include com.h2database dependency as well.

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.howtodoinjava</groupId>
	<artifactId>hibernate-hello-world</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.3.7.Final</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.200</version>
        </dependency>
        <dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
	 <build>
        <sourceDirectory>src/main/java</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

5. Hibernate Configuration

Notice the connection parameters use the H2 database related properties.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<property name="hibernate.connection.driver_class">org.h2.Driver</property>
		<property name="hibernate.connection.url">jdbc:h2:mem:test</property>
		<property name="hibernate.connection.username">sa</property>
		<property name="hibernate.connection.password"></property>
		<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
		<property name="show_sql">true</property>
		<property name="hbm2ddl.auto">create-drop</property>
		<mapping class="com.howtodoinjava.hibernate.test.dto.EmployeeEntity"></mapping>
	</session-factory>
</hibernate-configuration>

4.6. Entity class

package hibernate.test.dto;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import org.hibernate.annotations.OptimisticLockType;

@Entity
@org.hibernate.annotations.Entity(optimisticLock = OptimisticLockType.ALL)
@Table(name = "Employee", uniqueConstraints = {
		@UniqueConstraint(columnNames = "ID"),
		@UniqueConstraint(columnNames = "EMAIL") })
public class EmployeeEntity implements Serializable {

	private static final long serialVersionUID = -1798070786993154676L;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "ID", unique = true, nullable = false)
	private Integer employeeId;

	@Column(name = "EMAIL", unique = true, nullable = false, length = 100)
	private String email;

	@Column(name = "FIRST_NAME", unique = false, nullable = false, length = 100)
	private String firstName;

	@Column(name = "LAST_NAME", unique = false, nullable = false, length = 100)
	private String lastName;

	// Accessors and mutators for all four fields
}

4.7. Hibernate Session Factory

This is important. org.hibernate.cfg.Configuration is used for bootstrapping Hibernate.

Here, we define all the configuration options and entity definitions in hibernate.cgf.xml and build the SessionFactory in single statement.

package com.howtodoinjava.hibernate.test;

import java.io.File;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static final SessionFactory sessionFactory = buildSessionFactory();
	 
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure(new File("hibernate.cgf.xml")).buildSessionFactory();
 
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
 
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
 
    public static void shutdown() {
    	// Close caches and connection pools
    	getSessionFactory().close();
    }
}

Please do not forget to use the correct path of hibernate.cgf.xml.

8. Demo

package com.howtodoinjava.hibernate.test;

import org.hibernate.Session;

import com.howtodoinjava.hibernate.test.dto.EmployeeEntity;

public class TestHibernate {
	
	public static void main(String[] args) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
       
		//Add new Employee object
		EmployeeEntity emp = new EmployeeEntity();
		emp.setEmail("demo-user@mail.com");
		emp.setFirstName("demo");
		emp.setLastName("user");
		
		session.save(emp);
		
		session.getTransaction().commit();
		HibernateUtil.shutdown();
	}
}

The above code will create a new table employee in the database and insert one row in this table. In logs, you can verify the insert statement which got executed.

Hibernate: drop table Employee if exists

Hibernate: create table Employee (ID integer generated by default as identity, EMAIL varchar(100) 
not null, FIRST_NAME varchar(100) not null, LAST_NAME varchar(100) not null, primary key (ID))

Hibernate: alter table Employee add constraint UK_ardf0f11mfa6tujs3hflthwdv unique (EMAIL)

Hibernate: insert into Employee (ID, EMAIL, FIRST_NAME, LAST_NAME) values (null, ?, ?, ?)

Hibernate: drop table Employee if exists

If you face problem in running above hibernate hello world example, drop me a comment and I will be glad to discuss the problem with you.

Happy Learning!!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

38 thoughts on “Hibernate Hello World Example”

  1. can you guide me how to use this guide ??? i started it from the very first page of Hibernate Tutorials , going all the way down to link ” Hibernate 3 introduction and writing hello world application ” , after opening it I went to this link and started learning over there , creating maven project, importing into ecllipse , what is happening in step 5,6 . Where did all those properties and dependencies came from ???

    Reply
    • This project is a maven application , simply run the project from eclipse , you will see the output and logs in the console only.

      Reply
  2. Hi, I am trying to follow the sample, but have a problem to buld the source code provided. After getting the code (unpacking it to disk) and importing it into Eclipse, I convented teh project into Maven. Unfortunatelly it still doesnt build. it is complaining:
    Project ‘hibernate-test’ is missing required library: ‘/Users//.m2/repository/org/hibernate/hibernate/3.2.1.ga/hibernate-3.2.1.ga.jar’
    I looked at the dependencies and they look fine – at least for me.
    Any idea how to fix it?

    Reply
    • never mind … I just removed it from references and added hibernate-core into maven dependencies. I also had to choose higher version of ConnectorJ, in order to solve security issue with MySQL. now it works.

      Reply
  3. Hi,

    i m following your example and this is the errors i got. I suspect that it cant find the hibernate.cfg.xml file.

    "C:\Program Files\JetBrains\IntelliJ IDEA 2019.2.2\jbr\bin\java.exe" "
    Exception in thread "main" java.lang.ExceptionInInitializerError
    	at db.HibernateUtil.buildSessionFactory(HibernateUtil.java:20)
    	at db.HibernateUtil.(HibernateUtil.java:9)
    	at Main.main(Main.java:8)
    Caused by: java.lang.NoClassDefFoundError: org/hibernate/cfg/Mappings
    	at java.base/java.lang.ClassLoader.defineClass1(Native Method)
    	at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
    	at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174)
    	at java.base/jdk.internal.loader.BuiltinClassLoader .defineClass(BuiltinClassLoader.java:802)
    	at java.base/jdk.internal.loader.BuiltinClassLoader .findClassOnClassPathOrNull(BuiltinClassLoader.java:700)
    	at java.base/jdk.internal.loader.BuiltinClassLoader .loadClassOrNull(BuiltinClassLoader.java:623)
    	at java.base/jdk.internal.loader.BuiltinClassLoader .loadClass(BuiltinClassLoader.java:581)
    	at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader .loadClass(ClassLoaders.java:178)
    	at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    	at db.HibernateUtil.buildSessionFactory(HibernateUtil.java:15)
    	... 2 more
    Caused by: java.lang.ClassNotFoundException: org.hibernate.cfg.Mappings
    	at java.base/jdk.internal.loader.BuiltinClassLoader .loadClass(BuiltinClassLoader.java:583)
    	at java.base/jdk.internal.loader.ClassLoaders $AppClassLoader.loadClass(ClassLoaders.java:178)
    	at java.base/java.lang.ClassLoader.loadClass (ClassLoader.java:521)
    	... 12 more
    

    my hibernate.cfg.xml file is in project name labb1\\src\\main\\resources\\hibernate.cfg.xml

    Reply
  4. Hibernate: insert into employee_2 (EMAIL, First_Name, LAST_NAME) values (?, ?, ?)
    May 31, 2019 12:16:29 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
    WARN: SQL Error: 1146, SQLState: 42S02
    May 31, 2019 12:16:29 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
    ERROR: Table 'hibernate_practice_1.employee_2' doesn't exist
    org.hibernate.exception.SQLGrammarException: could not execute statement
    	at org.hibernate.exception.internal.SQLExceptionTypeDelegate
    .convert(SQLExceptionTypeDelegate.java:63)
    	at org.hibernate.exception.internal.StandardSQLExceptionConverter
    .convert(StandardSQLExceptionConverter.java:42)
    	at org.hibernate.engine.jdbc.spi.SqlExceptionHelper
    .convert(SqlExceptionHelper.java:113)
    	
    	at demo_1.TestHibernate_Employee_1.main(TestHibernate_Employee_1.java:39)
    Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'hibernate_practice_1.employee_2' doesn't exist
    	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    	at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    	
    	... 28 more
    May 31, 2019 12:16:29 PM org.hibernate.engine.jdbc.connections.internal
    .DriverManagerConnectionProviderImpl$PoolState stop
    INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/hibernate_practice_1?useSSL=false]
    May 31, 2019 12:16:29 PM org.hibernate.engine.jdbc.connections.internal
    .DriverManagerConnectionProviderImpl$PooledConnections close
    ERROR: Connection leak detected: there are 1 unclosed connections upon shutting down pool jdbc:mysql://localhost:3306/hibernate_practice_1?useSSL=false
    Reply
  5. It gives an error as: could not find file: hibernate.cgf.xml
    I am using eclipse IDE and i made my hibernate.cfg.xml file in src folder of project too

    Reply
  6. Hi Lokesh, Thanks for wonderful tutorials. I have a basic question. What is the need for mapping tag in configure file. Won’t the Entity annotation take care of mapping the entity class?

    Reply
  7. Hi. Can you please explain the meaning of

    Transient Objects: Instances of persistent classes that are not currently associated with a Session

    It is not clear to me, if they are persistent, how can they be transient?

    Thanks

    Reply
    • In TestHibernate.java, we created an instance of EmployeeEntity and it was transient until we called session.save(emp);.
      In more clear words, transient instances has no representation in the database (no corresponding row) and no identifier value set in them.

      Reply
  8. Hi Lokesh,

    “while Hibernates JPA implementation is code that meets the API as defined by JPA and provides the under the hood functionality”.
    If i am not wrong hibernate-jpa provider don’t need cfg.xml file whereas hibernate provider need it unless you are not explicitly setting properties in Configuration().

    Regards,
    Himansu

    Reply
  9. Hi Lokesh,

    I have basic question regarding when, why we should use hibernate/JDBC Spring(DI/AOP)/CoreJava?
    When(and why) we should choose hibernate or jdbc or other ORM? what are the advantages of one over the other?
    If I have a application with some 20 tables and I want to build some application using those 20 tables? would you suggest Hibernate?
    What technology would you choose – Spring, Hibernate or Just coreJava/Hibernate or coreJava/JDBC or Spring/JDBC and why?

    I know there are lot of resources/discussion available online, but I would like to know from you. Please suggest.

    ThankYou,
    Ravikanth

    Reply
    • Hi Ravi, Its very good (i.e. difficult) question to answer. But let me put my thoughts at this very moment (a good debate might change them and I am open for it).
      1) If you working on a small utility type project (e.g. data importer or exporter). I will recommend to use JDBC directly as it provides good control as well as performance.
      2) If you are working on a project which will be used by hundreds/thousands of users; then i will suggest to use hibernate (not so popular advise). Though all below features you can achieve with JBDC as well, but cost would be longer development time and possibly buggy code as frameworks have been refined with help of thousands community members over years.

      – Automatic Transaction Support
      – Inbuilt caching capabilities
      – DB schema non-dependent code

      Reply
  10. Hi Lokesh,

    Awesome work!!! Too impressive!!!

    The way u r explaining is not complicating the things.

    So pls describe as simple as possible because simple things reach a lot.

    Reply
  11. Hi Lokesh.. I have a question…… there are other orm tools like iBatis , toplink etc available in the java framework.. Why Hibernate is most demanding & generally used?

    Reply
    • Puneet, I have worked on hibernate and iBatis both. Based on my experience I would say that if your domain objects are similar to DB tables/columns and you do not need any complex SQL control then go for hibernate. Else choose iBatis. iBatis really gives you great control over complex database queries. It gives you almost all features (e.g. caching) which hibernate provides.
      But here is a catch. iBatis demands extra code/config (sql-maps i.e. mapping between java objects and database columns), which hibernate takes care for you.
      Development time is considerably short in Hibernate in comparison to iBatis, but you loose the flexibility which iBatis provide.

      Note: I have compared hibernate and iBatis based on my experience. Other frameworks I really can not comment on without further study.

      Reply
  12. what’s the Libraries you’ve used for this tutorial? why not attached with the source code ? if it is mention it for me please . thanks.

    Reply
    • Source code download link available in start and end of post. Please refer .classpath file for referenced jar files:


      <?xml version="1.0" encoding="UTF-8"?>
      <classpath>
      <classpathentry kind="src" path="src/test/java" output="target/test-classes" including="**/*.java"/>
      <classpathentry kind="src" path="src/main/java" including="**/*.java"/>
      <classpathentry kind="output" path="target/classes"/>
      <classpathentry kind="var" path="M2_REPO/javax/transaction/jta/1.1/jta-1.1.jar"/>
      <classpathentry kind="var" path="M2_REPO/javax/persistence/persistence-api/1.0/persistence-api-1.0.jar"/>
      <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
      <classpathentry kind="var" path="M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar"/>
      <classpathentry kind="var" path="M2_REPO/antlr/antlr/2.7.6/antlr-2.7.6.jar"/>
      <classpathentry kind="var" path="M2_REPO/commons-collections/commons-collections/3.1/commons-collections-3.1.jar"/>
      <classpathentry kind="var" path="M2_REPO/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar"/>
      <classpathentry kind="var" path="M2_REPO/xml-apis/xml-apis/1.0.b2/xml-apis-1.0.b2.jar"/>
      <classpathentry kind="var" path="M2_REPO/javassist/javassist/3.4.GA/javassist-3.4.GA.jar"/>
      <classpathentry kind="var" path="M2_REPO/org/slf4j/slf4j-api/1.5.6/slf4j-api-1.5.6.jar"/>
      <classpathentry kind="var" path="M2_REPO/org/slf4j/slf4j-log4j12/1.5.6/slf4j-log4j12-1.5.6.jar"/>
      <classpathentry kind="var" path="M2_REPO/log4j/log4j/1.2.14/log4j-1.2.14.jar"/>
      <classpathentry kind="var" path="M2_REPO/org/hibernate/hibernate-commons-annotations/3.0.0.ga/hibernate-commons-annotations-3.0.0.ga.jar"/>
      <classpathentry kind="var" path="M2_REPO/commons-logging/commons-logging/1.0.4/commons-logging-1.0.4.jar"/>
      <classpathentry kind="var" path="M2_REPO/org/hibernate/hibernate-annotations/3.3.0.ga/hibernate-annotations-3.3.0.ga.jar"/>
      <classpathentry kind="var" path="M2_REPO/org/hibernate/hibernate/3.2.1.ga/hibernate-3.2.1.ga.jar"/>
      <classpathentry kind="var" path="M2_REPO/net/sf/ehcache/ehcache/1.2.3/ehcache-1.2.3.jar"/>
      <classpathentry kind="var" path="M2_REPO/asm/asm-attrs/1.5.3/asm-attrs-1.5.3.jar"/>
      <classpathentry kind="var" path="M2_REPO/cglib/cglib/2.1_3/cglib-2.1_3.jar"/>
      <classpathentry kind="var" path="M2_REPO/asm/asm/1.5.3/asm-1.5.3.jar"/>
      <classpathentry kind="var" path="M2_REPO/mysql/mysql-connector-java/5.1.6/mysql-connector-java-5.1.6.jar"/>
      </classpath>

      Reply
      • thanks for the prompt reply, but I’ve an error I don’t know why .

        I downloaded the sourcecode and then I extracted the .rar project and took the src folder and pom.xml and hibernate.cgf.xml files and created with them a new project with Netbeans IDE .

        after that I added the libraries required using properties>libraries>classthpath from the installation of hibernate framework and junit framework.

        then this error appeared .

        Initial SessionFactory creation failed.java.lang.IncompatibleClassChangeError: Implementing class
        Exception in thread “main” java.lang.ExceptionInInitializerError
        at hibernate.test.HibernateUtil.buildSessionFactory(HibernateUtil.java:20)
        at hibernate.test.HibernateUtil.(HibernateUtil.java:9)
        at hibernate.test.TestHibernate.main(TestHibernate.java:10)
        Caused by: java.lang.IncompatibleClassChangeError: Implementing class
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
        at hibernate.test.HibernateUtil.buildSessionFactory(HibernateUtil.java:14)
        … 2 more

        I know I didn’t follow this tutorial literally but this because I’ve a little bit fuzzy about using hibernate framework.

        hope that you can assist me and sorry for the long reply .
        thanks in advance .

        Reply
  13. Hi Lokesh gupta,
    i am learning alot from your tutorials.your tutorials awesome.I have a small doubt what is the purpose of this annotation?
    @org.hibernate.annotations.Entity(optimisticLock = OptimisticLockType.ALL)

    Reply
  14. Hello,
    thanks for the tutorial.
    I had to correct two things to make it work :

    – in hibernate.cfg.xml, you have to specify the mapping class, eg :

    – in the entity bean, you have to specify dynamicUpdate=true into the annotation Entity :
    @org.hibernate.annotations.Entity(optimisticLock = OptimisticLockType.ALL, dynamicUpdate = true)

    Reply
    • Thanks for pointing out. First is definitely a typo so I have corrected this in post itself. Regarding second, I am not sure. It worked for me without dynamic update.

      Anyways, as you have logged your observation here, it will definitely help someone if faced problem.

      Reply
    • hi, can you explain me clearly what does this mean

      @org.hibernate.annotations.Entity(optimisticLock = OptimisticLockType.ALL, dynamicUpdate = true)

      Reply
      • 1) Optimistic means….the table is open for read/write over entire network for all users/sessions. We can move the cursor, backward or forward dynamically.
        2) Pessimistic means… the table is open for read/write only for that current session. The other session users can not edit the same.

        If set the dynamic-update to true, which means exclude unmodified properties in the Hibernate’s SQL update statement. It means, that if in any transaction in a table, 10 columns are present and values got updated for 3 columns, then update statement created by hibernate will have only 3 column names.

        Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.