数据库两张表在springboot如何拿到两张表的数据
时间: 2023-11-16 20:50:31 浏览: 33
可以使用Spring Data JPA来操作数据库。首先需要定义两个实体类,分别对应两张表,然后使用JpaRepository来操作实体类对应的表。
例如,定义两个实体类User和Order:
```java
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// getters and setters
}
@Entity
@Table(name="order")
public class Order {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String productName;
private Double amount;
// getters and setters
}
```
然后定义两个JpaRepository接口UserRepository和OrderRepository:
```java
public interface UserRepository extends JpaRepository<User, Long> {
}
public interface OrderRepository extends JpaRepository<Order, Long> {
}
```
在需要使用两张表数据的地方,可以注入这两个Repository,并使用它们提供的方法来操作数据库:
```java
@Service
public class MyService {
@Autowired
private UserRepository userRepository;
@Autowired
private OrderRepository orderRepository;
public List<User> getAllUsers() {
return userRepository.findAll();
}
public List<Order> getAllOrders() {
return orderRepository.findAll();
}
}
```
这样就可以分别获取两张表的数据了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)