springboot查询mysql数据库
时间: 2023-04-22 07:00:52 浏览: 132
Spring Boot可以通过JdbcTemplate或者Spring Data JPA来查询MySQL数据库。
1. 使用JdbcTemplate
JdbcTemplate是Spring框架提供的一个用于简化JDBC操作的工具类。使用JdbcTemplate查询MySQL数据库的步骤如下:
1)在pom.xml文件中添加MySQL驱动依赖:
```
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8..23</version>
</dependency>
```
2)在application.properties文件中配置MySQL数据库连接信息:
```
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
3)在Java代码中使用JdbcTemplate查询MySQL数据库:
```
@Autowired
private JdbcTemplate jdbcTemplate;
public List<User> getUsers() {
String sql = "SELECT * FROM user";
List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
return users;
}
```
2. 使用Spring Data JPA
Spring Data JPA是Spring框架提供的一个用于简化JPA操作的工具类。使用Spring Data JPA查询MySQL数据库的步骤如下:
1)在pom.xml文件中添加Spring Data JPA和MySQL驱动依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8..23</version>
</dependency>
```
2)在application.properties文件中配置MySQL数据库连接信息:
```
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
```
3)定义实体类和Repository接口:
```
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "age")
private Integer age;
// 省略getter和setter方法
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
```
4)在Java代码中使用Repository查询MySQL数据库:
```
@Autowired
private UserRepository userRepository;
public List<User> getUsers() {
List<User> users = userRepository.findAll();
return users;
}
```
阅读全文