How can multiple tables be queried together in Spring Boot?
In Spring Boot, you can perform multi-table queries using JPA (Java Persistence API) and Hibernate.
Here is a common method for performing a multiple table join:
- Create entity classes: First, create entity classes corresponding to each table, and use annotations to map them to the tables in the database.
@Entity
@Table(name = "table1")
public class Table1 {
@Id
private Long id;
private String name;
// getters and setters
}
@Entity
@Table(name = "table2")
public class Table2 {
@Id
private Long id;
private String description;
// getters and setters
}
- Mapping between two entities in a one-to-one relationship.
- – One-to-Many
- Used to define a many-to-one relationship in a database mapping.
- A relationship where each instance of one entity can be associated with multiple instances of another entity.
@Entity
@Table(name = "table1")
public class Table1 {
@Id
private Long id;
private String name;
@OneToOne(mappedBy = "table1")
private Table2 table2;
// getters and setters
}
@Entity
@Table(name = "table2")
public class Table2 {
@Id
private Long id;
@OneToOne
@JoinColumn(name = "table1_id")
private Table1 table1;
// getters and setters
}
- A repository for handling basic CRUD operations.
- A repository that provides methods for easy interaction with a database in a Spring application is referred to as JpaRepository.
public interface Table1Repository extends JpaRepository<Table1, Long> {
}
public interface Table2Repository extends JpaRepository<Table2, Long> {
}
- Performing multi-table queries: In the business logic layer or service layer, you can use JPA’s query methods as needed to perform multi-table queries.
@Service
public class MyService {
@Autowired
private Table1Repository table1Repository;
@Autowired
private Table2Repository table2Repository;
public List<Table1> getTable1WithTable2() {
return table1Repository.findAll(); // 返回所有Table1,并自动联查关联的Table2
}
}
The above method can conveniently perform multi-table queries. Additionally, more complex multi-table queries can also be achieved using native SQL queries, JPQL queries, and other methods.