What is Hibernate in Spring Boot and how to use it

What is Hibernate in Spring Boot and how to use it

Hibernate is a popular Java ORM framework that provides a way to map Java objects to relational database tables. Spring Boot integrates Hibernate, making it easy to use Hibernate to operate the database when developing web applications. This article will explain what Hibernate in Spring Boot is and how to use it.

insert image description here

What is Hibernate?

Hibernate is a popular Java ORM framework that provides a way to map Java objects to relational database tables. Hibernate refers to the mapping between Java objects and database tables as Object Relational Mapping (ORM). Hibernate uses annotations or XML configuration to define object mapping, which can easily persist Java objects into relational databases.

Hibernate provides the following features:

  • Object Relational Mapping: Maps Java objects to relational database tables.
  • Transaction Management: Perform multiple database operations within a transaction.
  • Query: Use Hibernate Query Language (HQL) or SQL to query the database.
  • Caching: Hibernate provides some caching mechanisms to improve the performance of the application.

Hibernate is an open source framework that can be easily integrated with Spring Boot.

How to use Hibernate

Spring Boot provides automatic configuration of Hibernate, making it very easy to use Hibernate in Spring Boot applications. Here are the steps to use Hibernate:

add dependencies

To use Hibernate we need to add the following dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

This will import dependencies like Spring Data JPA and Hibernate.

Configure data source

In Spring Boot, we can use application.properties or application.yml files to configure data sources. Here is an example using a MySQL database:

spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

In this example, we specified the URL of the MySQL database, username, password, and driver class name.

Create entity class

In Hibernate, entity classes are the key to mapping Java objects to database tables. Entity classes typically have the following characteristics:

  • Mark with @Entityannotations.
  • Use @Idannotations to mark a field as a primary key.
  • Use @GeneratedValueannotations to generate primary key values.

Here is an example of a simple entity class:

@Entity
public class User {
    
    

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String email;

    // getters and setters
}

In this example, we have created an entity class called User which has id, name and email fields. We use @Idthe annotation to mark the id field as the primary key, and use @GeneratedValuethe annotation to generate the value of the primary key.

Create a repository

In Spring Boot, we can use Spring Data JPA to create a Repository, which provides a set of CRUD operations that make it very easy to access the database. Here is an example Repository:

public interface UserRepository extends JpaRepository<User, Long> {
    
    

}

In this example, we create an interface called UserRepository which inherits from JpaRepository. We use User as the entity class and Long as the primary key type.

Use Repositories

In a Spring Boot application, we can use the autowiring mechanism to inject Repositories. Here is an example using Repository:

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

    @Autowired
    private UserRepository userRepository;

    @GetMapping("")
    public List<User> getAllUsers() {
    
    
        return userRepository.findAll();
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
    
    
        return userRepository.findById(id).orElse(null);
    }

    @PostMapping("")
    public User createUser(@RequestBody User user) {
    
    
        return userRepository.save(user);
    }

    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user) {
    
    
        User oldUser = userRepository.findById(id).orElse(null);
        if (oldUser == null) {
    
    
            return null;
        }
        oldUser.setName(user.getName());
        oldUser.setEmail(user.getEmail());
        return userRepository.save(oldUser);
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
    
    
        userRepository.deleteById(id);
    }
}

In this example, we create a controller named UserController which injects UserRepository. We use the @GetMapping, @PostMapping, @PutMappingand @DeleteMappingannotations to define HTTP request handlers. These handlers use UserRepository for CRUD operations.

Summarize

Hibernate is a popular Java ORM framework that provides a way to map Java objects to relational database tables. Spring Boot integrates Hibernate, making it easy to use Hibernate to operate the database when developing web applications. Using Hibernate in Spring Boot requires adding dependencies, configuring data sources, creating entity classes, creating Repositories, and using Repositories for CRUD operations. Through the introduction of this article, you should have understood how to use Hibernate in Spring Boot.

Guess you like

Origin blog.csdn.net/2302_77835532/article/details/131590607