How to Create a Project using Spring MVC and Hibernate 5?
Spring MVC is a popular model view controller framework that handles dependency injection at run time. Hibernate 5 is an ORM framework that acts as an abstraction over the database. It allows interaction with the underlying database by removing any implementation details which is handled by hibernate. In this article, we will integrate Spring MVC and Hibernate 5 with an in-memory database h2.
- IDE (Preferably IntelliJ)
- Java 8+
After creating an empty project you will need some core dependencies which are required for a bootstrap setup. In the dependencies section of your pom.xml add the following dependencies
The spring-orm module provides integration with hibernate
Core hibernate module for the hibernate dependencies
commons dependency for connection pooling
helps generate boilerplate code for constructors/setters/getters etc
Hibernate requires certain configurations to bootstrap such as DB path, driver, username, password, etc. We are going to use the annotation-based configuration an XML-based configuration can also be used if needed.
Create a db.properties file:
db.properties file will contain the basic configurations of the database we will read this source to configure our hibernate session
# MySQL properties db.driver=org.h2.Driver db.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 db.username=sa db.password=sa # Hibernate properties hibernate.hbm2ddl.auto=create-drop hibernate.dialect=org.hibernate.dialect.H2Dialect
Configuring the Application
Create a configuration class to wire the details for hibernate and set up the session factory etc
model class for the entity/table
The persistence layer to persist the model in the database
service class to interact with the repository and persist items
This is the entry point of the application, we need to wire this configuration to the application context.
Hibernate: drop table user if exists Hibernate: create table user (id integer generated by default as identity, first_name varchar(255), last_name varchar(255), primary key (id)) Oct 17, 2022 3:44:14 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform] Hibernate: insert into user (id, first_name, last_name) values (null, ?, ?) Hibernate: select user0_.id as id1_0_0_, user0_.first_name as first_na2_0_0_, user0_.last_name as last_nam3_0_0_ from user user0_ where user0_.id=? User(id=1, firstName=john, lastName=doe)
Please Login to comment...