Spring and hibernate tutorial

Spring and hibernate tutorial DEFAULT

Java developers typically encounter the need to store data on a regular basis. If you’ve been developing for more than 15 years, you probably remember the days of JDBC in Java. Using JDBC can be tedious if you don’t like writing SQL. Not only that, but there’s nothing in JDBC that helps you create your database. Hibernate came along and changed everything by allowing you to map POJOs (plain ol’ Java objects) to database tables. Not only that, but it had a very Java-esque API that made it easy to create CRUD POJOs. Shortly after, Spring came along and added abstractions for Hibernate that took API simplification even further. Fast forward to today, and most Java applications use both Spring and Hibernate.

For some time now, developers have operated under one of two separate but distinct models to represent business entities. The relational model, which is prevalent in databases, and the object-oriented model. These two models are similar in that both work using similar structures to represent business logic, and they are distinct in that they were designed for different purposes: one to store data, other to describe behavior.

Use Hibernate Old Fashioned Way, without Spring

With the advent of Hibernate (and many similar tools) the Java EE team decided to propose a new pattern to guide ORM frameworks using a single language. The JPA (Java Persistence API) was created and it is entirely defined as Java annotations (besides XML) which increase code readability and maintainability. Below is an example of an ol’ school XML-based mapping and more current annotation based mapping for the same entity.

Xml-Based mapping

Annotation-based mapping

In this post, you are going to work in two different technology stacks. You’ll create a very simple project using Hibernate (JPA annotations), then move to a Spring Boot project doing the same thing. After that, you’ll be introduced to Project Lombok which will reduce your project’s lines-of-code counter even further. Then, you are going to expose the CRUD operations as REST endpoints secured with Okta, and OAuth 2.0.

Create a Project Using Hibernate

In this project, you are going to use core Hibernate functionality with JPA annotations. You are not addressing XML configuration as it is not commonly used nowadays.

The project is already implemented here on the branch. The database model is represented in the following model:

For simplicity’s sake, the database chose is an H2 Database, an in memory, small, 100% Java database, excellent for testing and development purposes. The project has two significant dependencies:

Each database table is mapped to an entity. table is represented by entity and is represented by . Let’s take a look into the entity:

You just need to add annotation for Hibernate to understand the database must have a table with the same class name. Also, the entity has an which means the attribute with it is an entity identifier. In this case, we defined how our ID’s will be automatically generated (the decision is up to Hibernate dialect).

Now, you are going to review a more complex relationship type on entity:

As you can see, there is a and a annotation. Those annotations represent, as the name says, a many-to-one relationship (when a single entity has many relationships with other entity). The annotation specifies the relationship must be made by a column in the One entity (Course, in this case) and specifies the constraint name. I always recommend specifying the foreign key name to help to debugging.

We have two DAO’s (Data Access Objects) on this project: and . They both extend a simple abstract class that has some common CRUD operations:

The abstract puts all CRUD logic into the same class. In the next sample, a new and better solution will be presented with Spring.

Hibernate uses a abstraction to communicate with the database and convert objects to relations and vice-versa. The framework also introduces its own query language called HQL(Hibernate Query Language). In the code above, HQL is represented on the method. The cool thing about HQL is you are querying objects and not tables and relationships. The Hibernate query engine will convert to SQL internally.

ACID (Atomic Consistent Isolated Durable) is a relational database key feature. It guarantees consistency between the data inserted through transactions. In other words: if you are running a transaction, all your operations are atomic and not influenced by other operations that may be running in the same database, at the same time. To fully accomplish this, Hibernate also has a abstraction. The code on shows how it works:

This class creates some data for our example database, and all the data is inserted using the same transaction: if an error occurs, all data are erased before any user can query them. To correctly implement this on raw hibernate, we call and . It is also important to call and not to use the same session all over the operation.

Last but not least, we have the configuration file ():

Note that we need to declare all entities with node. For debugging purposes, it is important to set as it is possible to identify possible mapping problems just by reading the generated SQL.

Now, just run the command below to run your project:

Phew! That’s a lot of code. Now we are going to remove a lot of then by introducing Spring Data.

Reduce Hibernate Boilerplate with Spring Boot

As you probably know, Spring Boot has a lot of magic under the hood. I have to say, using it together with Spring Data is awesome.

You need to create a new project using Spring Initializr with and dependencies. After the project is created, copy all package to the new project, without any changes. Then, add the annotation to class as follows:

Then, remove the original DAO’s. With Spring, and will be changed to interfaces and extend the interface. Spring automatically identifies you are creating a Repository (or DAO) class when you extend a interface. automatically delivers CRUD methods like save, delete, update, and list for your entity without any effort and with transaction support.

If you want to skip to a a pre built example you can grab the code from GitHub. Please, clone it and go to branch:

Now, to change how we fill in the database. Create a service class that is responsible for filling our H2 database with data:

Do you see how clean your code is when compared to the raw project? This happens because you have only one concern: maintain your business code sanely. While on your raw project you had to handle s and s, here we just need to add annotation to keep the entire method execution inside a database transaction. Besides, the tells Spring this method must be invoked after the context is fully loaded.

Add the following lines in file to show up all SQL executed and to create the database if it does not exists.

Also, keep in mind Spring Boot automatically discovered H2 dependencies and configured it as the database you are using without any manual configuration.

To execute this code (which simply adds the entities to an ephemeral database), just run on a console:

Remove Even More Code with Project Lombok

Have you read about Project Lombok? It works in compile level to reduce Java famous verbosity and add features that are not available in your current JDK version (e.g. val and var). In our case, we will remove all boilerplate in entities classes.

Check branch to see the final result. Now we just need to add the dependency:

And change our entities to:

Course

and Teacher

Every getter and setter will be automatically generated by Lombok thanks to annotation. and tells the tool the entity needs two constructors: one empty and another with all arguments that has annotation (or are final). There is another annotation that creates an constructor with all arguments, but we cannot use it as id attribute can be null (only persisted entities should have a non-null value).

Note: Lombok has a lot of compile-level stuff and works out-of-the-box with Maven and Spring. Some IDE’s needs a specific plugin to work without compilation problems. Check out Project Lombok’s IDE setup guide.

As in the previous step, you just need to run the command to see everything working if you do not believe in me.

Expose CRUD Operations as a REST Service with Spring Data REST

Now we will explore a microservice area. You are going to change the project to externalize the data into a REST API. Also, we will explore a little bit more about Spring Repositories.

About the magic thing, do you believe you just need to add a single dependency to publish your DAO’s as a REST API? Test it! Add the following dependency:

Run and HTTPie the following address:

Test with the other entities like students, teachers and courses and you’ll see all data we manually insert into the database. It is also possible to PUT, POST or DELETE to create, update or delete a registry, respectively.

There is another cool thing about Spring Data Repositories: you can customize them by creating methods into a predefined format. Example for :

All updates are available on the rest_repository branch of our Git Repository.

Secure Your Spring Boot Application with OAuth 2.0

Security is an important part of any application, and adding OAuth 2.0/OIDC support to any Spring Boot web application only takes few minutes!

Our project is a OAuth 2.0 resource server and, as such, does not handle login steps directly. It only validates that the request has valid authorization and roles.

First, you need to add the following Maven dependencies:

And update your class:

Now, you need to configure your file:

This will enable your REST endpoints to only accept authorized users.

Before you begin, you’ll need a free Okta developer account. Install the Okta CLI and run to sign up for a new account. If you already have an account, run . Then, run . Select the default app name, or change it as you see fit.

Copy your Client ID and paste it into the file (just change variable).

Now, start the application again. It’ll be locked and you will be unable to make any requests as all of them are now protected. You just need to acquire a token to connect.

First, create a new SPA application in Okta. Run . Select the default app name, or change it as you see fit. Choose Single-Page App and press Enter.

Use for the Redirect URI and set the Logout Redirect URI to .

An easy way to get an access token is to generate one using OpenID Connect Debugger. First, you must configure your application on Okta to use OpenID Connect’s implicit flow.

Run and open the resulting URL in your browser. Go to the Applications section and select the application you just created. Edit its General Settings and add Implicit (Hybrid) as an allowed grant type, with access token enabled. Then, make sure it has in its Login redirect URIs. Click Save and copy the client ID for the next step.

Now, navigate to the OpenID Connect Debugger website. Fill in your client ID, and use for the Authorize URI. The field must be filled but can contain any characters. Select token for the response type.

OpenID connect

Submit the form to start the authentication process. You’ll receive an Okta login form if you are not logged in or you’ll see the screen below with your custom token.

OpenID connect - getting token

The token will be valid for one hour so you can do a lot of testing with your API. It’s simple to use the token, just copy it and modify the curl command to use it as follows:

For this last step, you can check out the branch and see all the changes I made.

Learn More About Spring and REST APIs

Object-oriented and relational databases can be tricky, but the Spring team managed to create a straightforward way to integrate both of them and add some advanced features like REST API and OAuth 2.0 authentication.

Though JPA makes it easy to build great apps, big databases can have performance issues. It’s a great solution for fast development but does not substitute a proper SQL performance tuning that only an experienced DBA can do.

Although all database schemas in this post were created automatically by Hibernate, this is not the recommended path for enterprise applications as they are continually evolving and need to change live with minor downtime and be able to roll back.

In this tutorial, you learned about Hibernate, JPA, and Spring’s evolution toward better SQL integration via object-oriented languages. Over the course of the tutorial, you also continuously improved your code so you had better readability and followed better practices.

The source code for this tutorial is available on GitHub.

Here some articles on this blog that will help you for further understanding:

Like what you learned today? Follow us on Twitter, like us on Facebook, check us out on LinkedIn, and subscribe to our YouTube channel for more awesome content!

Sours: https://developer.okta.com/blog/2019/02/01/spring-hibernate-guide

Spring is one of the most used Java EE Framework and Hibernate is the most popular ORM framework. That’s why Spring Hibernate combination is used a lot in enterprise applications. Recently I have written a lot for Spring Tutorial and Hibernate Tutorial, so a post for spring hibernate integration was due for long time.

spring hibernate integration example tutorial

Spring Hibernate

Today in this tutorial, we will use Spring 4 and integrate it with Hibernate 3 and then update the same project to use Hibernate 4. Since there are a lot of versions for Spring and Hibernate both and Spring ORM artifact supports both Hibernate 3 and Hibernate 4, it’s good that I list all the dependencies I have used in my project.

Note that I have noticed that all spring and hibernate versions are not compatible, below versions have worked for me so I think they are compatible. If you are using some other versions and getting , then it means that they are not compatible. Mostly it’s because Hibernate classes are moved from one package to another causing this error. For example class is moved to in latest hibernate versions.

  • Spring Framework Version: 4.0.3.RELEASE
  • Hibernate Core and Hibernate EntityManager Version: 3.6.9.Final and 4.3.5.Final
  • Spring ORM Version: 4.0.3.RELEASE

Database Setup

I am using MySQL database for my project, so below setup.sql script will create the necessary table for this example.

Spring Hibernate Integration Example Project Structure

Below image shows the final project structure, we will go through each of the components one by one.

Spring-Hibernate-Integration-Example-Project

Maven Dependencies

We will first look into our pom.xml file for all the required dependencies and their versions.

Important Dependencies for Spring and Hibernate Integration Project are:

  • spring-context and spring-tx for core Spring functionalities. Notice that I am using version 4.0.3.RELEASE.
  • spring-orm dependency for Spring ORM support, it’s required for hibernate integration in our spring project.
  • hibernate-entitymanager and hibernate-core dependencies for Hibernate framework. Notice that version is 3.6.9.Final, for using Hibernate 4 all we need is to change it to 4.3.5.Final as commented in above pom.xml file.
  • mysql-connector-java for MySQL driver for database connection.

Model Class or Entity Bean

We can use Hibernate XML based mapping as well as JPA annotation based mapping. Here I am using JPA annotations for mapping because hibernate provides JPA implementation.

DAO Classes

We will implement two methods in our DAO classes, first to save the Person object into table and second that will fetch all the records from the table and returns the list of Persons.

Above DAO class implementation would be like below.

Notice that this is the only place where we are using Hibernate related classes. This pattern makes our implementation flexible and easy to migrate from one technology to another. For example, if we want to use iBatis ORM framework, all we need is to provide a DAO implementation for iBatis and then change the spring bean configuration file.

In above example, I am using Hibernate session transaction management. But we can also use Spring declarative transaction management using annotation, read more at Spring Transaction Management.

Spring Bean Configuration File for Hibernate 3 Integration

Let’s first look at the spring bean configurations we need for Hibernate 3 integration, we will look into detail later on.

There are two ways we can provide database connection details to Hibernate, first by passing everything in and second by creating a DataSource and then passing it to hibernate. I prefer the second approach, that’s why we have Apache Commons DBCP dependency to create a by setting database connection properties.

For Spring and Hibernate 3 integration, Spring ORM provides two classes – when hibernate mappings are XML based and for annotations based mapping. I have provided simple bean configuration of in comments, if you are using XML based mappings. extends class, so it has all the basic properties for hibernate integration.

The properties are self understood and mostly hibernate related, so I will not go into much detail for them. But if you are wondering from where hibernateProperties, annotatedClasses are coming, you need to look into the bean class source code.

Notice the bean definition of personDAO, like I said earlier if we have to switch to some other ORM framework, we need to change the implementation class here and set any other properties we need.

Spring 4 Hibernate 3 Test Program

Our setup is ready now, let’s write a simple program to test our application.

When we execute above program, we get a lot of output related to Hibernate because I haven’t setup logging properly, but that’s out of scope of this tutorial. However we get following output generated by our program.

Spring 4 Hibernate 4 integration changes

Now let’s change our application to use Hibernate 4 instead of Hibernate 3. For this migration, we need to make only following configuration changes.

  1. Change the hibernate version to 4.3.5.Final in the pom.xml file, as shown in comments above.
  2. Change the spring bean configuration file, till now you must have figured out that Spring bean configuration file is the key for integration of spring and hibernate framework. Below spring bean configuration file will work for Spring 4 and Hibernate 4 versions.

    For hibernate 4, we need to use for SessionFactory bean, Spring ORM has merged both the classes for Hibernate 3 and there is a single class now, this is good to avoid confusion. All the other configurations are same as before.

That’s it, our project is successfully migrated to Hibernate 4, neat isn’t it. Just change the class to use for beans configuration and it will work fine, you will get same output as before.

You can download the final project from below link and play around with more configurations to learn more.

Download Spring Hibernate Integration Project

Sours: https://www.journaldev.com/3524/spring-hibernate-integration-example-tutorial
  1. Disney channel shows ranked
  2. Citrix osf osf healthcare
  3. Sebastian x oc
  4. Does wood ranch delivery

Hibernate and Spring Integration

next →← prev

We can simply integrate hibernate application with spring application.

In hibernate framework, we provide all the database information hibernate.cfg.xml file.

But if we are going to integrate the hibernate application with spring, we don't need to create the hibernate.cfg.xml file. We can provide all the information in the applicationContext.xml file.


Advantage of Spring framework with hibernate

The Spring framework provides HibernateTemplate class, so you don't need to follow so many steps like create Configuration, BuildSessionFactory, Session, beginning and committing transaction etc.

So it saves a lot of code.

Understanding problem without using spring:

Let's understand it by the code of hibernate given below:

As you can see in the code of sole hibernate, you have to follow so many steps.

Solution by using HibernateTemplate class of Spring Framework:

Now, you don't need to follow so many steps. You can simply write this:


Methods of HibernateTemplate class

Let's see a list of commonly used methods of HibernateTemplate class.

No.MethodDescription
1) void persist(Object entity) persists the given object.
2) Serializable save(Object entity) persists the given object and returns id.
3) void saveOrUpdate(Object entity) persists or updates the given object. If id is found, it updates the record otherwise saves the record.
4) void update(Object entity) updates the given object.
5) void delete(Object entity) deletes the given object on the basis of id.
6) Object get(Class entityClass, Serializable id) returns the persistent object on the basis of given id.
7) Object load(Class entityClass, Serializable id) returns the persistent object on the basis of given id.
8) List loadAll(Class entityClass) returns the all the persistent objects.

Steps

Let's see what are the simple steps for hibernate and spring integration:

  1. create table in the database It is optional.
  2. create applicationContext.xml file It contains information of DataSource, SessionFactory etc.
  3. create Employee.java file It is the persistent class
  4. create employee.hbm.xml file It is the mapping file.
  5. create EmployeeDao.java file It is the dao class that uses HibernateTemplate.
  6. create InsertTest.java file It calls methods of EmployeeDao class.

Example of Hibernate and spring integration

In this example, we are going to integrate the hibernate application with spring. Let's see the directory structure of spring and hibernate example.

spring hibernate example with directory structure
1) create the table in the database

In this example, we are using the Oracle as the database, but you may use any database. Let's create the table in the oracle database


2) Employee.java

It is a simple POJO class. Here it works as the persistent class for hibernate.


3) employee.hbm.xml

This mapping file contains all the information of the persistent class.


4) EmployeeDao.java

It is a java class that uses the HibernateTemplate class method to persist the object of Employee class.


5) applicationContext.xml

In this file, we are providing all the informations of the database in the BasicDataSource object. This object is used in the LocalSessionFactoryBean class object, containing some other informations such as mappingResources and hibernateProperties. The object of LocalSessionFactoryBean class is used in the HibernateTemplate class. Let's see the code of applicationContext.xml file.

hibernate template

File: applicationContext.xml


6) InsertTest.java

This class uses the EmployeeDao class object and calls its saveEmployee method by passing the object of Employee class.

Now, if you see the table in the oracle database, record is inserted successfully.


download this example (developed using MyEclipse IDE)


Enabling automatic table creation, showing sql queries etc.

You can enable many hibernate properties like automatic table creation by hbm2ddl.auto etc. in applicationContext.xml file. Let's see the code:

If you write this code, you don't need to create table because table will be created automatically.

Next TopicSpring and jpa integration



← prevnext →



Sours: https://www.javatpoint.com/hibernate-and-spring-integration

In this spring 5 hibernate 5 annotation example tutorial, learn to create Spring 5 MVC web application, handle form submission, integrate hibernate 5 to connect to backend database and adding hibernate validator for input form fields validation.

We will create a simple screen where we can add user fields (name and email). These details will be first validated and then stored in HSQL database using hibernate. The page will list down all stored users as well.

Table of Contents 1. Development Environment 2. Project Structure 3. Maven Dependencies 4. Configure DispatcherServlet 5. Spring WebMVC Configuration 6. Hibernate Configuration 7. Spring Controller and Path Mappings 8. Service and DAO layer 9. View and Messages 10. Demo

1. Development Environment

  • Eclipse Neon.2
  • JDK 1.8
  • Spring 5.2.0.RELEASE
  • Hibernate 5.2.11.Final
  • Hibernate validator 5.4.1.Final
  • Servlets 3.1.0
  • HSQLDB 1.8.0.10
  • Tomcat 7 maven plugin 2.2

2. Project Structure

This project has typical maven web application structure.

Spring5 WebMVC Project Structure

2.1. Class Diagram

Class Diagram

3. Maven Dependencies

Find project dependencies used to run this example in file.

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd; <modelVersion>4.0.0</modelVersion> <groupId>com.howtodoinjava.spring5.demo</groupId> <artifactId>spring5-mvc-hibernate-example</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <failOnMissingWebXml>false</failOnMissingWebXml> <spring.version>5.2.0.RELEASE</spring.version> <hibernate.version>5.2.11.Final</hibernate.version> <hibernate.validator>5.4.1.Final</hibernate.validator> <c3p0.version>0.9.5.2</c3p0.version> <jstl.version>1.2.1</jstl.version> <tld.version>1.1.2</tld.version> <servlets.version>3.1.0</servlets.version> <jsp.version>2.3.1</jsp.version> <hsqldb.version>1.8.0.10</hsqldb.version> </properties> <dependencies> <!-- Spring MVC Dependency --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring ORM --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <!-- Hibernate Core --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <!-- Hibernate-C3P0 Integration --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>${hibernate.version}</version> </dependency> <!-- c3p0 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>${c3p0.version}</version> </dependency> <!-- Hibernate Validator --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>${hibernate.validator}</version> </dependency> <!-- JSTL Dependency --> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>javax.servlet.jsp.jstl-api</artifactId> <version>${jstl.version}</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>${tld.version}</version> </dependency> <!-- Servlet Dependency --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlets.version}</version> <scope>provided</scope> </dependency> <!-- JSP Dependency --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>${jsp.version}</version> <scope>provided</scope> </dependency> <!-- HSQL Dependency --> <dependency> <groupId>hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>${hsqldb.version}</version> </dependency> </dependencies> <build> <sourceDirectory>src/main/java</sourceDirectory> <resources> <resource> <directory>src/main/resources</directory> </resource> </resources> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <path>/</path> </configuration> </plugin> </plugins> </build> </project>

4. DispatcherServlet Configuration

With the release of the Servlet 3.0 spec it became possible to configure your Servlet Container with (almost) no xml. For this there is the in the Servlet specification. In this class you can register filters, listeners, servlets etc. as you would traditionally do in a .

Spring provides which knows how to handle classes. class implements which internally implements . It registers a (optionally) and a and allows you to easily add configuration classes to load for both classes and to apply filters to the DispatcherServlet and to provide the servlet mapping.

package com.howtodoinjava.demo.spring.config; public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[] { HibernateConfig.class }; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[] { WebMvcConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }

5. Spring WebMVC Configuration

Spring MVC configuration using annotation configuration is given below.

package com.howtodoinjava.demo.spring.config; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.validation.Validator; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.howtodoinjava.demo.spring"}) public class WebMvcConfig implements WebMvcConfigurer { @Bean public InternalResourceViewResolver resolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setViewClass(JstlView.class); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); return resolver; } @Bean public MessageSource messageSource() { ResourceBundleMessageSource source = new ResourceBundleMessageSource(); source.setBasename("messages"); return source; } @Override public Validator getValidator() { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.setValidationMessageSource(messageSource()); return validator; } }
  1. defines options for customizing or adding to the default Spring MVC configuration enabled through the use of .
  2. enables default Spring MVC configuration and registers Spring MVC infrastructure components expected by the .
  3. indicates that a class declares one or more methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.
  4. annotation is used to specify the base packages to scan. Any class which is annotated with @Component and @Configuration will be scanned.
  5. helps in mapping the logical view names to directly view files under a certain pre-configured directory.
  6. accesses resource bundles using specified basenames (here it is messages).
  7. bootstraps a and exposes it through the Spring interface as well as through the JSR-303 interface and the interface itself.

6. Hibernate Configuration

Hibernate configuration used in the example is based on hibernate Java based configuration.

package com.howtodoinjava.demo.spring.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScans; import org.springframework.context.annotation.Configuration; import org.springframework.orm.hibernate5.HibernateTransactionManager; import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.howtodoinjava.demo.spring.model.User; @Configuration @EnableTransactionManagement public class HibernateConfig { @Autowired private ApplicationContext context; @Bean public LocalSessionFactoryBean getSessionFactory() { LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean(); factoryBean.setConfigLocation(context.getResource("classpath:hibernate.cfg.xml")); factoryBean.setAnnotatedClasses(User.class); return factoryBean; } @Bean public HibernateTransactionManager getTransactionManager() { HibernateTransactionManager transactionManager = new HibernateTransactionManager(); transactionManager.setSessionFactory(getSessionFactory().getObject()); return transactionManager; } }
  • creates a Hibernate . This is the usual way to set up a shared Hibernate SessionFactory in a Spring application context.
  • enables Spring’s annotation-driven transaction management capability.
  • binds a Hibernate Session from the specified factory to the thread, potentially allowing for one thread-bound Session per factory. This transaction manager is appropriate for applications that use a single Hibernate for transactional data access, but it also supports direct access within a transaction i.e. plain JDBC.
<?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.archive.autodetection">class,hbm</property> <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property> <property name="hibernate.connection.username">sa</property> <property name="hibernate.connection.password"></property> <property name="hibernate.connection.url">jdbc:hsqldb:mem:howtodoinjava</property> <property name="hibernate.hbm2ddl.auto">create</property> <property name="hibernate.c3p0.min_size">5</property> <property name="hibernate.c3p0.max_size">20</property> <property name="hibernate.c3p0.acquire_increment">2</property> <property name="hibernate.c3p0.acquire_increment">1800</property> <property name="hibernate.c3p0.max_statements">150</property> </session-factory> </hibernate-configuration>

7. Spring Controller and REST Mappings

Controller class has two simple REST mappings for and operations. If input fields are not validated, then return the same form bean to display error messages. Else return refreshed view.

package com.howtodoinjava.demo.spring.controller; import java.util.Locale; import javax.validation.alid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import com.howtodoinjava.demo.spring.model.User; import com.howtodoinjava.demo.spring.service.UserService; @Controller public class UserController { @Autowired private UserService userService; @GetMapping("/") public String userForm(Locale locale, Model model) { model.addAttribute("users", userService.list()); return "editUsers"; } @ModelAttribute("user") public User formBackingObject() { return new User(); } @PostMapping("/addUser") public String saveUser(@ModelAttribute("user") @Valid User user, BindingResult result, Model model) { if (result.hasErrors()) { model.addAttribute("users", userService.list()); return "editUsers"; } userService.save(user); return "redirect:/"; } }

8. Service and DAO layer

Service and DAO layer are normal service components annotated with and annotations. annotation is applied at service layer for transaction support.

Read More: @Service and @Repository Anootations

public interface UserService { void save(User user); List<User> list(); } @Service public class UserServiceImp implements UserService { @Autowired private UserDao userDao; @Transactional public void save(User user) { userDao.save(user); } @Transactional(readOnly = true) public List<User> list() { return userDao.list(); } } public interface UserDao { void save(User user); List<User> list(); } @Repository public class UserDaoImp implements UserDao { @Autowired private SessionFactory sessionFactory; @Override public void save(User user) { sessionFactory.getCurrentSession().save(user); } @Override public List<User> list() { @SuppressWarnings("unchecked") TypedQuery<User> query = sessionFactory.getCurrentSession().createQuery("from User"); return query.getResultList(); } } package com.howtodoinjava.demo.spring.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; @Entity @Table(name = "TBL_USERS") public class User { @Id @GeneratedValue @Column(name = "USER_ID") private Long id; @Column(name = "USER_NAME") @Size(max = 20, min = 3, message = "{user.name.invalid}") @NotEmpty(message="Please Enter your name") private String name; @Column(name = "USER_EMAIL", unique = true) @Email(message = "{user.email.invalid}") @NotEmpty(message="Please Enter your email") private String email; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }

9. View and Message Resource

Finally, JSP file used and messages resource bundle used.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Spring5 MVC Hibernate Demo</title> <style type="text/css"> .name}</td> <td>${user.email}</td> </tr> </c:forEach> </table> </body> </html> user.name.invalid = Name must be between {2} and {1} characters. user.email.invalid = Please enter valid email address.

10. Demo

Let’s run the application using maven tomcat7 plugin. Execute maven goal : .

URL:

Initial Screen
Invalid Input Validation
Valid Form Submission

Check Server logs.

Hibernate: call next value for hibernate_sequence Hibernate: insert into TBL_USERS (USER_EMAIL, USER_NAME, USER_ID) values (?, ?, ?) Hibernate: select user0_.USER_ID as USER_ID1_0_, user0_.USER_EMAIL as USER_EMA2_0_, user0_.USER_NAME as USER_NAM3_0_ from TBL_USERS user0_

I hope that you have find this spring hibernate web application example to set you start for developing your own application. This is primarily for beginners, yet it will help you build any Spring MVC with hibernate integration example with annotations.

Happy Learning !!

Sourcecode Download

Let us know if you liked the post. That’s the only way we can improve.

Sours: https://howtodoinjava.com/spring5/webmvc/spring5-mvc-hibernate5-example/

Tutorial spring and hibernate

For sure. Frank tears rolled down my cheeks, each the size of a pea. - No, do not despair, this is a mild form, you will gradually recover, but you need intensive therapy. I know one ancient method of treatment, but not the fact that it will work.

JPA And Hibernate Tutorial For Beginners with Spring Boot and Spring Data JPA

And they were very attracted to it. I have never understood men who dream of having sex with a lesbian. What's the point. If lesbians are lesbians because for them a man is not a sexual object.

Now discussing:

So swiftly and harmoniously that I did not have time to react and was swaddled. In some seconds. The guards silently checked the reliability of the fixation and also silently left the room.



853 854 855 856 857