Spring Boot + Spring Data JPA + PostgreSQL example

This article shows how to use Spring Web MVC to create REST endpoints for CRUD database operations using the Spring Data JPA and PostgreSQL. At the end of the tutorial, we will use Docker to start a PostgreSQL container to test the Spring Boot REST endpoints using curl commands. We will use Spring Test and …

Read more

Spring Boot MySQL : Table ‘DB_NAME.hibernate_sequence’ doesn’t exist

Spring Boot + Spring Data JPA + MySQL, and hits the following error message when the application starts : Tested with : Spring Boot 2.1.2.RELEASE mysql-connector-java 8.0.13 Hibernate 5.3.7 java.sql.SQLSyntaxErrorException: Table ‘DB_NAME.hibernate_sequence’ doesn’t exist at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:974) at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1024) at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) at org.hibernate.id.enhanced.TableStructure.executeQuery(TableStructure.java:216) at org.hibernate.id.enhanced.TableStructure.access$300(TableStructure.java:46) application.properties spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=mkyong …

Read more

Spring Boot + Spring Data JPA + MySQL example

This article shows how to use Spring Web MVC to create REST endpoints to perform CRUD database operations using the Spring Data JPA and MySQL. At the end of the tutorial, we will use Docker to start a MySQL container to test the Spring Boot REST endpoints using curl commands. We will use Spring Test …

Read more

Spring Boot – Show Hibernate SQL query

Add the following lines in application.properties to log the Hibernate SQL query. application.properties #show sql statement logging.level.org.hibernate.SQL=debug #show sql values logging.level.org.hibernate.type.descriptor.sql=trace 1. org.hibernate.SQL=debug application.properties logging.level.org.hibernate.SQL=debug 1.1 Select query. Console 2017-02-23 21:36:42 DEBUG org.hibernate.SQL – select customer0_.id as id1_0_, customer0_.created_date as created_date2_0_, customer0_.email as email3_0_, customer0_.name as name4_0_ from customer customer0_ 2. org.hibernate.type.descriptor.sql=trace application.properties logging.level.org.hibernate.SQL=debug logging.level.org.hibernate.type.descriptor.sql=trace …

Read more

Spring Boot + Spring Data JPA + Oracle example

In this article, we will show you how to create a Spring Boot + Spring Data JPA + Oracle + HikariCP connection pool example. Tools used in this article : Spring Boot 1.5.1.RELEASE Spring Data 1.13.0.RELEASE Hibernate 5 Oracle database 11g express Oracle JDBC driver ojdbc7.jar HikariCP 2.6 Maven Java 8 1. Project Structure A …

Read more

JPA optimistic lock exception in Java Development

This post explains the JPA technology and its use in java development. Experts of java development India are explaining the use case of technologies- JPA and Hibernate, MySql database, Maven. Read this post and know what they want to say. Technology: JPA stands for the Java Persistence API which is the standard from Sun Micro …

Read more

Spring Security + Hibernate XML Example

In this tutorial, we will show you how to integrate Hibernate 4 in Spring Security, XML configuration example. Note For annotation version, please read this Spring Security + Hibernate Annotation Example. Technologies used : Spring 3.2.8.RELEASE Spring Security 3.2.3.RELEASE Hibernate 4.2.11.Final MySQL Server 5.6 JDK 1.6 Maven 3 Eclipse 4.3 Quick Notes Create a session …

Read more

java.lang.ClassNotFoundException: org.hibernate.service.jta.platform.spi.JtaPlatform

Spring 3.2.x + Hibernate 4.3.x integration, hits JtaPlatform ClassNotFoundException, search the project classpath, find out that JtaPlatform is at different package? hibernate-core.4.3.5.Final.jar org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform Error message shows org.hibernate.service.jta.platform.spi.JtaPlatform Caused by: java.lang.NoClassDefFoundError: org/hibernate/service/jta/platform/spi/JtaPlatform at org.springframework.orm.hibernate4.SpringSessionContext.<init>(SpringSessionContext.java:56) ~[spring-orm-3.2.8.RELEASE.jar:3.2.8.RELEASE] … 40 common frames omitted Caused by: java.lang.ClassNotFoundException: org.hibernate.service.jta.platform.spi.JtaPlatform //… pom.xml <!– Hibernate ORM –> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.5.Final</version> </dependency> <!– …

Read more

Hibernate component mapping example

Hibernate component represents as a group of values or properties, not entity (table). See following tutorial to understand how component works in Hibernate. 1. Customer Table See below customer table. Customer table, SQL script in MySQL database. CREATE TABLE `customer` ( `CUST_ID` int(10) unsigned NOT NULL AUTO_INCREMENT, `CUST_NAME` varchar(10) NOT NULL, `AGE` int(10) unsigned NOT …

Read more

Hibernate – Many-to-Many example – join table + extra column (Annotation)

In this tutorial, we show you how to use Hibernate to implements “many-to-many table relationship, with extra column in the join table“. Note For many to many relationship with NO extra column in the join table, please refer to this @many-to-many tutorial 1. Many-to-many table + extra columns in join table The STOCK and CATEGORY …

Read more

Hibernate – Many-to-Many example (Annotation)

In this tutorial, it will reuse the entire infrastructure of the previous “Hibernate many to many example – XML mapping” tutorial, enhance it to support Hibernare / JPA annotation. Note For many to many with extra columns in join table, please refer to this tutorial. Project Structure Review the new project structure of this tutorial. …

Read more

Hibernate – Unable to insert if column named is keyword, such as DESC

Problem A table named “category” in MySQL database, contains a “DESC” keyword as column name. CREATE TABLE `category` ( `CATEGORY_ID` int(10) unsigned NOT NULL AUTO_INCREMENT, `NAME` varchar(10) NOT NULL, `DESC` varchar(255) NOT NULL, PRIMARY KEY (`CATEGORY_ID`) USING BTREE ); Hibernate XML mapping file <hibernate-mapping> <class name="com.mkyong.stock.Category" table="category" catalog="mkyongdb"> … <property name="desc" type="string"> <column name="DESC" not-null="true" …

Read more

Hibernate – One-to-Many example (Annotation)

In this tutorial, it will reuse the entire infrastructure of the previous “Hibernate one to many relationship example – XML mapping” tutorial, enhance it to support Hibernate / JPA annotation. Project Structure Review the new project structure of this tutorial. Note Since Hibernate 3.6, annotation codes are merged into the Hibernate core module, so, the …

Read more

Hibernate – One-to-One example (Annotation)

In this tutorial, it will reuse the entire infrastructure of the previous “Hibernate one to one relationship example – XML mapping” tutorial, enhance it to support Hibernate / JPA annotation. Project Structure See the final project structure of this tutorial. Note Since Hibernate 3.6, annotation codes are merged into the Hibernate core module, so, the …

Read more

How to configure DBCP connection pool in Hibernate

Note Due to bugs in the old DBCP code, Hibernate is no longer maintain DBCP-based connection provider, read this Hibernate thread. Now, Apache DBCP is back to active development, and many bugs are fixed and it’s more stable now. Even Hibernate doesn’t come with connection provider like C3P0 and Proxool, but you still can configure …

Read more

Hibernate – Could not find C3P0ConnectionProvider

Problem Configured Hibernate to use “c3p0” connection pool, but hits following warning : //… 2011-04-25_12:18:37.190 WARN o.h.c.ConnectionProviderFactory – c3p0 properties is specificed, but could not find org.hibernate.connection.C3P0ConnectionProvider from the classpath, these properties are going to be ignored. 2011-04-25_12:18:37.191 INFO o.h.c.DriverManagerConnectionProvider – Using Hibernate built-in connection pool (not for production use!) //… Look like “org.hibernate.connection.C3P0ConnectionProvider” is …

Read more

How to configure logging in Hibernate – Logback

In this tutorial, we show how to integrate Logback logging framework with Hibernate. Tools and Technologies used in this tutorial : Hibernate 3.6.3.Final slf4j-api-1.6.1 logback-core-0.9.28 logback-classic-0.9.28 Eclipse 3.6 Maven 3.0.3 1. Get SLF4j + Logback To use logback in Hibernate web application, you need 3 libraries : slf4j-api.jar logback-core logback-classic File : pom.xml <project …> …

Read more

Maven 3 + Hibernate 3.6 + Oracle 11g Example (Annotation)

This tutorial will reuse and modify the previous Hibernate3.6 XML mapping tutorial, but replace the Hibernate mapping file (hbm) with Hibernate / JPA Annotation code. Technologies in this article : Maven 3.0.3 JDK 1.6.0_13 Hibernate 3.6.3.final Oracle 11g 1. pom.xml No change in pom.xml file, all previous Hibernate3.6 XML mapping tutorial dependency can be reused. …

Read more

Hibernate – The type AnnotationConfiguration is deprecated

Problem Working with Hibernate 3.6, noticed the previous “org.hibernate.cfg.AnnotationConfiguration“, is marked as “deprecated“. Code snippets … import org.hibernate.cfg.AnnotationConfiguration; //… private static SessionFactory buildSessionFactory() { try { return new AnnotationConfiguration().configure().buildSessionFactory(); } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } The code is still working, just keep displaying the deprecated …

Read more

Maven 3 + Hibernate 3.6 + Oracle 11g Example (XML Mapping)

In this article, we show you how to integrate Maven3, Hibernate3.6 and Oracle11g together. In the end of this article, you will create a Java project with Maven, and insert a record into Oracle database via Hibernate framework. Tools & technologies used in this article : Maven 3.0.3 JDK 1.6.0_13 Hibernate 3.6.3.final Oracle 11g 1. …

Read more

java.lang.ClassNotFoundException : javassist.util.proxy.MethodFilter

Problem Using Hibernate 3.6.3, but hits this javassist not found error, see below for error stacks : Caused by: java.lang.NoClassDefFoundError: javassist/util/proxy/MethodFilter … at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:77) … 16 more Caused by: java.lang.ClassNotFoundException: javassist.util.proxy.MethodFilter at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:252) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) … 21 more Solution javassist.jar is missing, and you …

Read more

Hibernate Error – Collection has neither generic type or OneToMany.targetEntity()

Problem In Hibernate development, defined one to many relationship via annotation. package com.mkyong.user.model; @Entity @Table(name = "USER", schema = "MKYONG") public class User implements java.io.Serializable { private Set address = new HashSet(0); //… @OneToMany(orphanRemoval=true, cascade=CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user") public Set getAddress() { return this.address; } } But it hits following exception : …

Read more

WebSphere 7 & javax/persistence/OneToMany.orphanRemoval() error

Problem In Hibernate development, contains a model class with JPA @OneToMany annotation : @OneToMany( cascade=CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user") public Set<Debit> getDebits() { return this.debits; } When web application is deployed on WebSphere 7, it hit following error message : Caused by: java.lang.NoSuchMethodError: javax/persistence/OneToMany.orphanRemoval()Z at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:1912) at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:707) … 118 more P.S hibernate-jpa-2.0-api-1.0.0.Final.jar …

Read more

org.hibernate.AnnotationException: Collection has neither generic type or OneToMany.targetEntity()

Problem See following Hibernate mapping via annotation, which is generated by NetBean’s Hibernate Tool. File : Stock.java package com.mkyong.stock.model; //… @Entity @Table(name = "stock", catalog = "mkyong"); public class Stock implements java.io.Serializable { //… private Set stockCategories = new HashSet(0); @OneToMany(fetch = FetchType.LAZY, mappedBy = "stock") public Set getStockCategories() { return this.stockCategories; } public void …

Read more

Hibernate Error : JavaReflectionManager cannot be cast to MetadataProviderInjector

Problem Using Hibernate annotation, after upgraded Hibernate version from v3.2.7 to v3.6, it hits following error message : Caused by: java.lang.ClassCastException: org.hibernate.annotations.common.reflection.java.JavaReflectionManager cannot be cast to org.hibernate.annotations.common.reflection.MetadataProviderInjector Here’s the list of the Hibernate annotation libraries : hibernate3-3.6.0.Final.jar hibernate-annotations-3.4.0.GA.jar hibernate-commons-annotations-3.0.0.GA.jar Solution Hibernate annotation module is merged into Hibernate core module since v3.5 (if not mistake). In …

Read more

java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.(Z)V

Problem Ant project, doing Spring + Hibernate (annotation) development, but hits following error message : Caused by: java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(Z)V Here’s the list of the main jar files, included asm-3.3.1.jar, but still hits the above error message? hibernate-3.2.7.ga.jar hibernate-annotations-3.4.0.GA.jar hibernate-commons-annotations-3.0.0.GA.jar spring-2.5.6.jar asm-3.3.1.jar Solution A classic problem in Ant project, you have to manage dependency library manually, …

Read more

java.lang.ClassNotFoundException: org.objectweb.asm.Type

Problem In Hibernate development, it hits… java.lang.ClassNotFoundException: org.objectweb.asm.Type Solution This is caused by the missing of asm.jar, you can get it from asm official website, or get it via Maven <dependency> <groupId>asm</groupId> <artifactId>asm</artifactId> <version>3.3.1</version> </dependency>

java.lang.ClassFormatError : Absent Code attribute in method that is not native or abstract in class file …

Problem A very strange and rare problem, happened in JPA or Hibernate development. Caused by: java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/GenerationType at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(Unknown Source) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$000(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) …

Read more

java.lang.ClassNotFoundException: javax.transaction.TransactionManager

Problem In JPA or Hibernate development, it hits the following error message : Caused by: java.lang.ClassNotFoundException: javax.transaction.TransactionManager at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) … 23 more Solution The javax.transaction.TransactionManager is a class inside the J2EE SDK library “javaee.jar“, you are missing this jar …

Read more

java.lang.ClassNotFoundException: javax.persistence.Entity

Problem In JPA or Hibernate development, it hits the following error message : Caused by: java.lang.ClassNotFoundException: javax.persistence.Entity at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) … 24 more Solution The javax.persistence.Entity is a class inside the J2EE SDK library “javaee.jar“, you are missing this jar …

Read more

java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter

Problem In Hibernate development, it’s common to hits the following error message. SEVERE: Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/classes/config/database/spring/HibernateSessionFactory.xml]: Invocation of init method failed; nested exception is Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer] … … Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown …

Read more

Hibernate – save image into database

To save an image into database, you need to define a table column as blob data type in MySQL, or equivalent binary type in others database. In Hibernate side, you can declare a byte array variable to store the image data. Download this example – Hibernate-Image-Example.zip Here’s an Maven project to use Hibernate to save …

Read more

Spring AOP transaction management in Hibernate

Transaction management is required to ensure the data integrity and consistency in database. Spring’s AOP technique is allow developers to manage the transaction declarative. Here’s an example to show how to manage the Hibernate transaction with Spring AOP. P.S Many Hibernate and Spring configuration files are hidden, only some important files are shown, if you …

Read more

Maven + (Spring + Hibernate) Annotation + MySql Example

Download It – Spring-Hibernate-Annotation-Example.zip In last tutorial, you use Maven to create a simple Java project structure, and demonstrate how to use Hibernate in Spring framework to do the data manipulation works(insert, select, update and delete) in MySQL database. In this tutorial, you will learn how to do the same thing in Spring and Hibernate …

Read more

Maven + Spring + Hibernate + MySql Example

This example will use Maven to create a simple Java project structure, and demonstrate how to use Hibernate in Spring framework to do the data manipulation works(insert, select, update and delete) in MySQL database. Final project structure Your final project file structure should look exactly like following, if you get lost in the folder structure …

Read more

Hibernate Error – java.lang.NoClassDefFoundError: javax/transaction/Synchronization

Problem This is caused by missing of the “jta.jar“, usually happened in Hibernate transaction development. java.lang.NoClassDefFoundError: javax/transaction/Synchronization at org.hibernate.impl.SessionImpl.<init>(SessionImpl.java:213) at org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:473) at org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:497) at org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:505) at com.mkyong.common.App.main(App.java:13) Caused by: java.lang.ClassNotFoundException: javax.transaction.Synchronization at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClassInternal(Unknown Source) … 5 more …

Read more

Hibernate – fetching strategies examples

Hibernate has few fetching strategies to optimize the Hibernate generated select statement, so that it can be as efficient as possible. The fetching strategy is declared in the mapping relationship to define how Hibernate fetch its related collections and entities. Fetching Strategies There are four fetching strategies 1. fetch-“join” = Disable the lazy loading, always …

Read more

Hibernate Criteria examples

Hibernate Criteria API is a more object oriented and elegant alternative to Hibernate Query Language (HQL). It’s always a good solution to an application which has many optional search criteria. Example in HQL and Criteria Here’s a case study to retrieve a list of StockDailyRecord, with optional search criteria – start date, end date and …

Read more