Spring Boot JPA Hibernate Login Example

Spring Boot JPA Hibernate Login Example thumbnail
49K
By Dhiraj 10 March, 2019

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-project-gen

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.

application.properties
spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = root
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
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.

UserController.java
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

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

    @PostMapping("/login")
    public ApiResponse login(@RequestBody LoginDto loginDto){
        return userService.login(loginDto);
    }
}

SignUpDto.java
public class SignUpDto {

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

}
LoginDto.java
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.

@Transactional
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserDaoImpl userDaoImpl;

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

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

    }

    private void validateSignUp(SignUpDto signUpDto) {
    }
}

ApiResponse.java

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.

UserDao.java
public interface UserDao extends JpaRepository {

    User findByUsername(String username);

    User findByEmail(String email);
}

UserDaoImpl.java
@Repository
public class UserDaoImpl {

    @Autowired
    private EntityManager em;

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

}

Entity class definition for ORM.

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

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

Testing Application

Below are the POSTMAN screenshots for login and signup request.

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

Conclusion

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

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.

Further Reading on Spring Boot