SpringBoot开发经常使用奥Spring Boot连接MySQL,下面详解Spring Boot连接MySQL步骤@mikechen
- 在 pom.xml 文件中添加 mysql-connector-java 依赖项。
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
- 在 application.properties 或 application.yml 文件中配置MySQL连接信息。
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=myuser spring.datasource.password=mypassword spring.datasource.driver-class-name=com.mysql.jdbc.Driver
- 创建一个 @Component 类来管理数据源。
import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; @Configuration public class DatabaseConfig { @Autowired private DataSource dataSource; @Bean public JdbcTemplate jdbcTemplate() { return new JdbcTemplate(dataSource); } }
- 在需要访问数据库的类中使用 JdbcTemplate 进行操作。
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; @Repository public class UserRepository { @Autowired private JdbcTemplate jdbcTemplate; public List<User> findAll() { String sql = "SELECT * FROM users"; return jdbcTemplate.query(sql, (rs, rowNum) -> new User( rs.getLong("id"), rs.getString("name"), rs.getInt("age") )); } }
- 在需要使用数据库操作的类中,通过 @Autowired 注解注入 UserRepository 类,并调用其相应的方法。
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserRepository userRepository; public List<User> findAllUsers() { return userRepository.findAll(); } }
通过以上步骤,你可以在Spring Boot中轻松地连接MySQL数据库并进行数据操作。
更多Spring Boot内容请查看:SpringBoot框架(万字图文全面详解)
mikechen
mikechen睿哥,10年+大厂架构经验,资深技术专家,就职于阿里巴巴、淘宝、百度等一线互联网大厂。
关注「mikechen」公众号,获知最新一线技术干货!
