Spring Boot JPA Hibernate Login Example

author-image   By Dhiraj,   10 March, 2019 5K

In this article, we will be creating a sample spring boot and hibernate JPA example and add the functionality of user registration and login. This example can be a starting point to get started with a full-fledged spring boot and hibernate app. The registration process will create an entry in the database and during the sign-in process, the user credentials will be validated from DB. We will be using Mysql for this purpose.

We will try to keep this application as simple as possible to provide a starting point for beginners. For all the advanced tutorials you can visit these list Spring Security Tutorials, Spring Boot Tutorials

Technology Used

  • Spring Boot 2

  • Hibernate

  • MySQL

Generating Spring Boot Project

Head over to start.spring.io and generate a sample spring boot project. We have selected 3 required artifacts - Web, MySQL and JPA.


Spring Boot JPA and Hibernate Configurations

In this example, we are not adding any extra bean configuration for defining our EntitymanagerFactory or Datasource as Spring Boot automatically creates one based on the artifacts available in the pom file. We have DB configurations added in the application.properties and Spring Boot is smart enough to detect it and create our beans as per these configurations. You can definitely define your bean configurations if you wish to customisze these default bean definitions.

You can visit my another article - Spring Boot Hibernate Integration to customise these behaviour as per your requirements.

spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = root
spring.jpa.show-sql = true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

Spring Controller Implementation

First, let us expose our endpoint for the login and registration process. The implementation is very simple.It has 2 methods defined as signUp() and login() to accept the request from the client. The client can be a POSTMAN request or a browser based application. You can visit this article Spring Boot Angular for an intregation with an Angular app.

public class UserController {

    private UserService userService;

    public ApiResponse signUp(@RequestBody SignUpDto signUpDto){
        return userService.signUp(signUpDto);

    public ApiResponse login(@RequestBody LoginDto loginDto){
        return userService.login(loginDto);

public class SignUpDto {

    private String firstName;
    private String lastName;
    private String email;
    private String username;
    private String password;
	//getters and setters

public class LoginDto {

    private String username;
    private String password;
	//getters and setters

Login and Registration Service Implementation

The login and signup logic goes here. The signup method validates the user creation process. Also, you can encrypt the password before saving to DB. The login method checks if user is present in the DB and returns success response for a username and password match. You can visit this article Spring Security and Bcrypt for spring security and Bcrypt integration.

Here, we are injecting UserDao as well as UserDaoImpl. UserDao uses Spring JPA to perform DB operations whereas UserDaoImpl has implementation with Hibernate for performing DB operations.

public class UserServiceImpl implements UserService {

    private UserDao userDao;

    private UserDaoImpl userDaoImpl;

    public ApiResponse signUp(SignUpDto signUpDto) {
        User user = new User();
        //can use Bcrypt
        BeanUtils.copyProperties(signUpDto, user);
        return new ApiResponse(200, "success", user);

    public ApiResponse login(LoginDto loginDto) {
        User user = userDao.findByUsername(loginDto.getUsername());
        if(user == null) {
            throw new RuntimeException("User does not exist.");
            throw new RuntimeException("Password mismatch.");
        return new ApiResponse(200, "Login success", null) ;


    private void validateSignUp(SignUpDto signUpDto) {


This class provides uniform API response.

public class ApiResponse {

    private int status;
    private String message;
    private Object result;

    public ApiResponse(int status, String message, Object result){
        this.status = status;
        this.message = message;
        this.result = result;

    public int getStatus() {
        return status;


Spring JPA and Hibernate Implementation

As discussed above UserDao provides Spring JPA implementation whereas UserDaoImpl provides implementation with Hibernate. You can viit this article for a complete explanation of Spring Boot JPA Integration.

public interface UserDao extends JpaRepository {

    User findByUsername(String username);

    User findByEmail(String email);

public class UserDaoImpl {

    private EntityManager em;

    public User save(User user) {
        Session session = em.unwrap(Session.class);
        return user;


Entity class definition for ORM.

@Table(name = "USERS")
public class User {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String firstName;
    private String lastName;
    private String email;
    private String username;
    private String password;

Testing Application

Below are the POSTMAN screenshots for login and signup request.

spring-boot-JPA-signup spring-boot-JPA-login


In this article, we created a sample spring boot and hibernate JPA example and add functionality of user registration and login.

If You Appreciate This, You Can Consider:

  • Like us at: Facebook or follow us at Twitter
  • Share this article on social media or with your teammates.
  • We are thankful for your never ending support.

About The Author


I am an energetic professional who enjoys the challenges involved in working with people and resolving real-time problems. Technical expertise in building highly scalable, distributed and self-healing cloud applications. Technical Skills: Java/J2EE, Spring Framework, Hibernate, Angular, Reactive Programming, Microservices, Rest APIs, Kafka, ELK, etc.

Further Reading on Spring Boot

1 Spring Boot Mongodb Crud

2 Spring Boot Mongodb Configuration

3 File Upload Angularjs Spring Boot Rest

4 Spring Mvc Contentnegotiating Viewresolver Example

5 Spring Jms Activemq Integration Example

6 Spring Mvc Angularjs Integration Example

7 Spring Hibernate Integration Example Javaconfig

8 Writing Junit Tests In Spring4 Mvc

9 Spring Ehcache Cacheable Example Javaconfig