Skip to main content


Showing posts with the label Hibernate

Java - How to print Hibernate query parameters on console?

Introduction In this post, we will learn how to print Hibernate Query parameters using log4j. Requirments log4j-api-2.13.1.jar log4j-core-2.13.1.jar Step 1 Place the above two log4j jars inside the lib directory. For web applications, the lib directory is located inside the WEB-INF folder. Step 2 Create a file by the name of  log4j2.xml and place it inside your src folder. Step 3 Place the following XML code inside the  log4j2.xml file <configuration status="WARN"> <appenders> <console name="LogToConsole" target="SYSTEM_OUT"> <patternlayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"> </patternlayout></console> </appenders> <loggers> <logger additivity="false" level="debug" name="org.myapp"> <appenderref ref="LogToConsole"> &

Hibernate 5.4.4 - How to fix hibernate depreciation warnings?

Problem Recently we migrated Hibernate to the latest version i.e. 5.4.4. Multiple depreciation warnings appeared in our code i.e. The type Query<R> is deprecated The method setString(String, String) from the type Query is deprecated The method uniqueResult() from the type Query is deprecated The method setBoolean(String, boolean) from the type Query is deprecated The method setLong(String, long) from the type Query is deprecated Solution Existing Change To import org.hibernate.Query; import org.hibernate. query .Query; query . setLong ( "serviceId" , serviceId ) ; query . setParameter ( "serviceId" , serviceId ); query . setBoolean ( "isDelete" ,Boolean. FALSE ) ; query . setParameter ( "isDelete" ,Boolean. FALSE ) ; query . setString ( "serviceNo" , serviceNo ) ; query . setParameter ( "serviceNo"

WARN orm.deprecation - HHH90000014: Found use of deprecated [] sequence-based id generator

Introduction  I upgraded Hibernate from version 4 to 5.4.4. Following warning was thrown by Hibernate WARN  orm.deprecation - HHH90000014: Found use of deprecated [] sequence-based id generator; use instead.  See Hibernate Domain Model Mapping Guide for details. http-nio-8080-exec-10 WARN  orm.deprecation - HHH90000014: Found use of deprecated [] sequence-based id generator; use instead.  See Hibernate Domain Model Mapping Guide for details. Old Code     @Id     @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_PERSON")     @SequenceGenerator(name = "SEQ_PERSON", sequenceName = "SEQ_PERSON_ID",allocationSize=1)     private Long id; SequenceGenerator is deprecated by Hibernate and we have to use either SequenceStyleGenerator or GenericGenerator instea

Hibernate - Could not instantiate id generator [entity-name=domainObject]

Exception Could not instantiate id generator [entity-name=Your DomainObject] Solution  <generator> or @GeneratedValue specifies the Java class that is used to generate a unique identifier to the mapped persistent class. Using increment  hbm.xml example <id name="id" type="java.lang.Long" column="id">        <generator class="increment" /> </id> Annotation example @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="ID") private Long id; Using database sequence hbm.xml example <id name="id" type="java.lang.Long" column="id">   <generator class="sequence">     <param name="sequence">SEQ_PERSON_ID</param>  </generator> </id> Annotation example @Id @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="PERSON_SEQ") @SequenceGenerator(name="PERSON_SEQ&qu

Hibernate 5.4.4 - select hibernate_sequence.nextval from dual

Exception http-nio-8080-exec-1 DEBUG hibernate.SQL - select hibernate_sequence.nextval from dual http-nio-8080-exec-1 WARN  spi.SqlExceptionHelper - SQL Error: 2289, SQLState: 42000 http-nio-8080-exec-1 ERROR spi.SqlExceptionHelper - ORA-02289: sequence does not exist org.hibernate.exception.SQLGrammarException: could not extract ResultSet at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert( at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert( Solution Default value for setting changed to true for 5.0, in previous versions it was set to false by default Add the following property to hibernate.cfg.xml <property name=""> false </property> OR Add the following property to the configuration properties.put("", " false &

Hibernate 5.4.4 - Instantiate an instance of SessionFactory

Introduction We will learn how to create an instance of SessionFactory using Hibernate 5.4.4 Code private static final SessionFactory sessionFactory; public static final String cfgFileLocation = "/hibernate.cfg.xml";  try {          StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()                                            .configure( cfgFileLocation ).build();           Metadata metadata = new MetadataSources( standardRegistry )             .getMetadataBuilder()             .applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE )             .build();     sessionFactory = metadata.getSessionFactoryBuilder()           .build();     } catch (Throwable ex) {                  System.out.println( "exception" );         throw new ExceptionInInitializerError(ex);     } Following exceptions are resolved through the above code java.lang.IllegalArgumentException: org.hibernate.hql.intern

hibernate-release-5.4.4.Final - Required Jars

Introduction Hibernate (Object Relational Mapping framework) is an implementation of Java Persistence API (JPA) specification.   Required Jars for Hibernate 5.4.4 Following Jars resided inside the required folder are the mandatory jars required for Hibernate 5.4.4 antlr-2.7.7.jar byte-buddy-1.9.11.jar classmate-1.3.4.jar dom4j-2.1.1.jar FastInfoset-1.2.15.jar hibernate-commons-annotations-5.1.0.Final.jar hibernate-core-5.4.4.Final.jar istack-commons-runtime-3.0.7.jar jandex-2.0.5.Final.jar javassist-3.24.0-GA.jar javax.activation-api-1.2.0.jar javax.persistence-api-2.2.jar jaxb-api-2.3.1.jar jaxb-runtime-2.3.1.jar jboss-logging-3.3.2.Final.jar jboss-transaction-api_1.2_spec-1.1.1.Final.jar stax-ex-1.8.jar txw2-2.3.1.jar Hibernate 5.4.4 release is compatible with  Java 8 or 11  JPA 2.2 References

Hibernate - How to maintain a single Session instance Per Thread?

Hibernate is an Object Relation mapping framework for Java language. It has more benefits over JDBC. Since I am using it since 2010, I have found that one of the biggest benefits of Hibernate is that code written using Hibernate is almost database independent and can be a key feature if one wants to shift the code base from one database to another. Using Hibernate, one has to be careful with the following two a) A singleton SessionFactory instance should be maintained throughout the application (if using a single database)  It can be easily done using either a static code block OR implementing the Singleton pattern. b) Single Session instance should be maintained per Thread This is a tricky part but luckily we have the ThreadLocal  to our rescue.  This class provides thread-local variables. Below is the code to maintain a single Session instance per Thread private static final ThreadLocal<Session> session = new ThreadLocal<Session>();    public static S