Using hibernate with spring boot
1. Maven dependency
In order to use hibernate with spring boot, we need to add the following dependency to the pom.xml file.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Because hibernate is the default implementation of JPA, it will be added to the project by just adding the JPA dependency.
We also need the dependency for our database, in our case we are going to use the h2 database you can use whichever you like.
Maven dependency for h2 database
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
2. Database configuration
After adding the database dependency we need to add the following configuration to application.properties
file to configure the database.
spring.datasource.url=jdbc:h2:mem:users
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
#enabling the H2 console
spring.h2.console.enabled=true
We also enabled the h2 console for the h2 database using the spring.h2.console.enabled=true
Note: This configuration might be a little different depending upon the database you chose.
3. Creating Entity
Now, we will create a user class, which will represent the user and we will use this class to save the user's info to the database.
User.java
package com.example.demo.User;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
4. User Repository
We also need to create a repository that will interact with the database and will work on the persistent layer of the application.
UserRepository.java
package com.example.demo.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
}
5. User Service
Next, we create a service class for our user where we will implement the business logic for the user.
UserService.java
package com.example.demo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User saveUser(User user){
return userRepository.save(user);
}
public User getUserById(int id){
return userRepository.findById(id).get();
}
public List<User> getAllUsers(){
return userRepository.findAll();
}
public User updateUser(User user){
User newUser = userRepository.findById(user.getId()).get();
newUser.setAge(user.getAge());
newUser.setName(user.getName());
return userRepository.save(newUser);
}
public void deleteUser(int id){
userRepository.delete(userRepository.findById(id).get());
}
}
Here we have only added the simple crud operations for keeping things simple as possible.
6. User Controller
The last step is to add a controller for the user which will handle all the requests for our user.
UserController.java
package com.example.demo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getUser(@PathVariable int id){
return userService.getUserById(id);
}
@GetMapping("/all")
public List<User> getAllUsers(){
return userService.getAllUsers();
}
@PostMapping("/")
public User saveUser(@RequestBody User user){
return userService.saveUser(user);
}
@PutMapping("/")
public User updateUser(@RequestBody User user){
return userService.updateUser(user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable int id){
userService.deleteUser(id);
}
}
This is all we needed to do. Now we are ready to use hibernate for interacting with the database.
7. Testing the application
Now we can run the application and test our app using the postman or any other Rest Client.
7.1. H2 console
After the application has started you can check the database for a user table that is created by the hibernate.
To access the H2 console you need to visit http://localhost:8080/h2-console
here you will see the login panel for the H2 database.
After entering the details which you configured in the application.properties
file you will be able to access the H2 database. In the database, you should see a user
table.
7.2. Performing the database operations
Now, it is time to perform the CRUD operations using the postman.
In the postman make a POST request to the http://localhost:8080
with the following data.
{
"name":"User1",
"age":"45"
}
This will save a new user to the database.
As you can see that the user info has been saved to the database successfully.
Now you can perform the other operations such as read, update, and delete using the hibernate as well.
8. Conclusion
In this article, we saw how to configure and use hibernate with spring boot. Hibernate can perform many more complex tasks than just CRUD operations with little ease.