Spring读取MySQL数据库指定内容
时间: 2024-05-03 11:22:40 浏览: 92
1. 添加MySQL依赖
在pom.xml文件中添加MySQL依赖
```xml
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
```
2. 配置数据源
在application.properties文件中配置数据源信息
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
3. 创建实体类
创建对应MySQL表的实体类,并使用JPA注解进行映射
```java
@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方法省略
}
```
4. 创建Repository
创建Repository接口,继承JpaRepository,并添加自定义方法
```java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByIdAndName(Long id, String name);
}
```
5. 调用自定义方法
在业务逻辑中调用自定义方法
```java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User getUserByIdAndName(Long id, String name) {
return userRepository.findByIdAndName(id, name);
}
}
```
以上就是使用Spring读取MySQL数据库指定内容的步骤。
阅读全文