使用Spring Boot连接MySQL数据库

在Spring Boot应用程序中连接MySQL数据库是非常常见的操作。在本文中,我们将演示如何使用IP地址连接MySQL数据库。

步骤一:添加MySQL依赖

首先,我们需要在pom.xml文件中添加MySQL依赖:

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

步骤二:配置MySQL连接信息

application.propertiesapplication.yml文件中配置MySQL连接信息,包括IP地址、用户名、密码等:

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

步骤三:创建实体类和Repository

创建一个实体类,并使用@Entity@Table等注解来映射数据表。然后创建一个Repository接口,继承JpaRepositoryCrudRepository来操作数据库。

@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;
    // getters and setters
}

public interface UserRepository extends JpaRepository<User, Long> {
}

步骤四:编写业务逻辑

编写业务逻辑,在Service层调用Repository来操作数据库:

@Service
public class UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
    
    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }
    
    // other CRUD methods
}

步骤五:控制器层

创建一个控制器层来处理HTTP请求,并调用Service层的方法:

@RestController
@RequestMapping("/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/")
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }
    
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }
    
    // other CRUD endpoints
}

饼状图表示连接IP地址

pie
    title 配置比例
    "IP地址" : 60
    "用户名" : 20
    "密码" : 20

以上是连接MySQL数据库的基本步骤,通过Spring Boot可以很方便地实现与MySQL数据库的交互。

在实际开发中,我们可以根据具体需求进行扩展,如配置连接池、实现事务管理等。希望本文能对您有所帮助,谢谢阅读!