How does SpringBoot connect to the database

Spring Boot is a popular Java development framework that can easily connect to various types of databases, both relational and non-relational. This article will introduce how Spring Boot connects to the database, including its principles and code examples.

insert image description here

1. The principle of Spring Boot connecting to the database

Spring Boot connects to the database by using Spring Data JPA. Spring Data JPA is part of Spring Data and is a persistence framework based on the JPA specification. It provides a simple way to interact with the database, and can easily implement basic CRUD operations.

Spring Boot can use a variety of different databases, including relational databases (such as MySQL, PostgreSQL, Oracle, and SQL Server) and non-relational databases (such as MongoDB). For each database, Spring Boot can use different drivers to connect.

Before connecting to the database, you need to specify the database connection information in the configuration file of the Spring Boot project. This information includes the URL of the database, username, password, and driver name. Spring Boot automatically loads this information and uses it to create the database connection.

2. Sample code for Spring Boot to connect to MySQL database

Below is a sample code for connecting to a MySQL database using Spring Boot. First, the MySQL driver dependency needs to be added in the pom.xml file:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.26</version>
</dependency>

Then, specify the connection information for the MySQL database in the application.properties file:

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

Here, we specify to connect to the MySQL database on the local host, the user name is "root", and the password is "123456".

Next, we create an entity class User to represent user information:

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String email;

    // getters and setters
}

Here, we use JPA annotations to specify the name of the entity class and the name of the table, as well as the generation strategy of the specified ID.

Then, we create a UserRepository interface that defines methods for manipulating user data:

public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByName(String name);
}

Here, we extend the JpaRepository interface and specify the entity class and ID type. This interface also defines a method for looking up users by name.

Finally, we create a UserController class that handles HTTP requests and uses UserRepository to access the database:

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserRepository userRepository;

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

    @GetMapping("/{name}")
    public List<User> getUsersByName(@PathVariable String name) {
        return userRepository.findByName(name);
    }

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

Here, we've used Spring MVC annotations to define how HTTP requests are handled. This class uses the Autowired annotation to automatically inject a UserRepository instance and use it to access the database.

3. Summary

This article introduces how Spring Boot connects to the database, including its principles and code examples. By using Spring Data JPA, Spring Boot can easily connect to various types of databases and implement basic CRUD operations. In actual development, you can access the database by modifying configuration files and creating entity classes, Repository interfaces, and controller classes.

Guess you like

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