springboot项目如何实现从MySQL数据库中查询数据
时间: 2023-05-30 20:04:00 浏览: 247
idea+springboot+mybatis+jsp+bootstrap实现从mysql查询出数据并显示(源码)
1. 配置pom.xml文件,添加MySQL驱动依赖
```
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
```
2. 配置application.properties文件,指定MySQL数据库连接信息
```
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
```
3. 创建数据实体类,使用JPA注解定义表名、字段名等信息
```
@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;
// 省略getters和setters方法
}
```
4. 创建数据访问层接口,继承JpaRepository,使用JPA内置方法实现数据访问
```
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByName(String name);
List<User> findByAgeGreaterThan(Integer age);
}
```
5. 在业务层中调用数据访问层接口方法,获取数据
```
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> findByName(String name) {
return userRepository.findByName(name);
}
public List<User> findByAgeGreaterThan(Integer age) {
return userRepository.findByAgeGreaterThan(age);
}
}
```
阅读全文