
在 spring boot 和 jpa 在应用程序中,当实体(例如 flight)与多个其他实体(例如(例如) airport、airline、airplane)存在 manytoone 关系通常在持久操作(如保存或更新)中,jpa 框架希望获得完整的相关实体对象。例如,flight 实体定义如下:
@Entity
@Table
public class Flight {
@Id
@Column(name = "flight_number")
private String flightNumber;
@ManyToOne
@JoinColumn(name = "origin")
private Airport origin; // 关联 Airport 对象
@ManyToOne
@JoinColumn(name = "destination")
private Airport destination; // 关联 Airport 对象
@Column(name = "departure_time")
private Timestamp departureTime;
@Column(name = "arrival_time")
private Timestamp arrivalTime;
@ManyToOne
@JoinColumn(name = "airline")
private Airline airline; // 关联 Airline 对象
@ManyToOne
@JoinColumn(name = "airplane")
private Airplane airplane; // 关联 Airplane 对象
private Time duration;
private int passengers;
// Getters and Setters
// ...
}
直接将外部输入的相关实体ID(如机场ID)、给航空公司ID赋值 Flight 实体中的 Airport 或 Airline 字段是不可行的,因为这些字段期望的是 Airport 或 Airline 类型对象,而不是简单的字符串或长整形ID。如果试图定制自己 @Query 并直接传输ID字符串更新,JPA 会因为类型不匹配而报错。
解决方案:DTOs 与服务层映射为了解决上述问题,最佳实践是引入数据传输对象(DTO)并在服务层进行映射。
1. 定义数据传输对象 (DTO)首先,创建一个 DTO 表示客户端请求的数据,包括相关实体 ID,而不是完整的对象。
import java.sql.Time;
import java.sql.Timestamp;
public record FlightRequest(
String flightNumber,
String airportOriginId, // 只输入启动机场ID
String airportDestinationId, // 只输入目的机场ID
Timestamp departureTime,
Timestamp arrivalTime,
String airlineId, // 仅引入航空公司ID
Long airplaneId, // 只是进入飞机ID
Time duration,
int passengers
// ... 其他字段
) {
}
这里使用了 Java 16+ 的 record 它是一种简单的特征 DTO 定义方法。如果使用旧版本。 Java,一个常规可以定义 Java 类,包括相应的字段、构造函数和 getter/setter。
2. 服务层处理逻辑在服务层,我们将接受 FlightRequest DTO,然后根据 DTO 中提供的 ID 从数据库中检索相应的相关实体,并将其设置为 Flight 实体中。
创建新航班 (addFlight)
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
@Service
public class FlightService {
private final FlightRepository flightRepository;
private final AirportRepository airportRepository;
private final AirlineRepository airlineRepository;
private final AirplaneRepository airplaneRepository;
public FlightService(FlightRepository flightRepository,
AirportRepository airportRepository,
AirlineRepository airlineRepository,
AirplaneRepository airplaneRepository) {
this.flightRepository = flightRepository;
this.airportRepository = airportRepository;
this.airlineRepository = airlineRepository;
this.airplaneRepository = airplaneRepository;
}
@Transactional
public Flight addFlight(FlightRequest flightRequest) {
if (flightRepository.existsById(flightRequest.flightNumber())) {
throw new IllegalStateException("航班号 " + flightRequest.flightNumber() + " 已存在");
}
Flight flight = new Flight();
// 根据ID搜索并设置相关实体,如果不存在,则抛出异常
Airport origin = airportRepository.findById(flightRequest.airportOriginId())
.orElseThrow(() -> new IllegalStateException("始发机场 " + flightRequest.airportOriginId() + " 不存在"));
flight.setOrigin(origin);
Airport destination = airportRepository.findById(flightRequest.airportDestinationId())
.orElseThrow(() -> new IllegalStateException("目的机场 " + flightRequest.airportDestinationId() + " 不存在"));
flight.setDestination(destination);
Airline airline = airlineRepository.findById(flightRequest.airlineId())
.orElseThrow(() -> new IllegalStateException("航空公司 " + flightRequest.airlineId() + " 不存在"));
flight.setAirline(airline);
Airplane airplane = airplaneRepository.findById(flightRequest.airplaneId())
.orElseThrow(() -> new IllegalStateException("飞机 " + flightRequest.airplaneId() + " 不存在"));
flight.setAirplane(airplane);
// 设置 Flight 的其他属性
flight.setFlightNumber(flightRequest.flightNumber());
flight.setDepartureTime(flightRequest.departureTime());
flight.setArrivalTime(flightRequest.arrivalTime());
flight.setDuration(flightRequest.duration());
flight.setPassengers(flightRequest.passengers());
return flightRepository.save(flight);
}
}
更新现有航班 (updateFlight)
乾坤圈新媒体矩阵管家
新媒体账号、门店矩阵智能管理系统
17
更新操作类似于创建,但需要根据主键进行更新 Flight 实体。
@Transactional
public Flight updateFlight(String flightNumber, FlightRequest flightRequest) {
Flight flight = flightRepository.findById(flightNumber)
.orElseThrow(() -> new IllegalStateException("航班号 " + flightNumber + " 不存在,不能更新"));
// 根据ID搜索并设置相关实体,如果不存在,则抛出异常
// 注:可根据业务需要判断是否需要更新相关实体
if (flightRequest.airportOriginId() != null) {
Airport origin = airportRepository.findById(flightRequest.airportOriginId())
.orElseThrow(() -> new IllegalStateException("始发机场 " + flightRequest.airportOriginId() + " 不存在"));
flight.setOrigin(origin);
}
if (flightRequest.airportDestinationId() != null) {
Airport destination = airportRepository.findById(flightRequest.airportDestinationId())
.orElseThrow(() -> new IllegalStateException("目的机场 " + flightRequest.airportDestinationId() + " 不存在"));
flight.setDestination(destination);
}
if (flightRequest.airlineId() != null) {
Airline airline = airlineRepository.findById(flightRequest.airlineId())
.orElseThrow(() -> new IllegalStateException("航空公司 " + flightRequest.airlineId() + " 不存在"));
flight.setAirline(airline);
}
if (flightRequest.airplaneId() != null) {
Airplane airplane = airplaneRepository.findById(flightRequest.airplaneId())
.orElseThrow(() -> new IllegalStateException("飞机 " + flightRequest.airplaneId() + " 不存在"));
flight.setAirplane(airplane);
}
// 更新 Flight 的其他属性
// 仅更新 FlightRequest 中非空字段,支持部分更新
Optional.ofNullable(flightRequest.departureTime()).ifPresent(flight::setDepartureTime);
Optional.ofNullable(flightRequest.arrivalTime()).ifPresent(flight::setArrivalTime);
Optional.ofNullable(flightRequest.duration()).ifPresent(flight::setDuration);
if (flightRequest.passengers() > 0) { // 假设乘客人数大于0,假设乘客人数大于0
flight.setPassengers(flightRequest.passengers());
}
// ... 更新其他属性
return flightRepository.save(flight); // Save方法将根据ID判断是插入还是更新
}性能优化:使用 getReferenceById
从 Spring Data JPA 2.7 版本开始,JpaRepository 接口提供了 getReferenceById(ID id) 方法(在旧版本中 getById(ID id))。这个方法与 findById 主要区别在于:
- findById: 会立即进行数据库查询,返回一个 Optional<T>,如果实体不存在,则返回 Optional.empty()。
- getReferenceById: 不会立即执行数据库查询,而是返回代理(Proxy)对象。只有当您尝试访问代理对象的非ID属性时,JPA 将实际数据加载到数据库中。这意味着,如果您只需要设置一个外部关联,而不访问关联实体的其他属性并使用它 getReferenceById 可以避免不必要的一次 SELECT 查询,从而提高性能。
使用 getReferenceById 优化服务层逻辑:
@Transactional
public Flight addFlightOptimized(FlightRequest flightRequest) {
if (flightRepository.existsById(flightRequest.flightNumber())) {
throw new IllegalStateException("航班号 " + flightRequest.flightNumber() + " 已存在");
}
Flight flight = new Flight();
// 使用 getReferenceById 获取相关实体的代理对象
// 注意:getReferenceById 不检查实体是否存在,如果ID不存在,后续访问代理对象将被抛出 EntityNotFoundException
// 因此,如果业务需要严格检查相关实体是否存在,仍建议使用 findById
flight.setOrigin(airportRepository.getReferenceById(flightRequest.airportOriginId()));
flight.setDestination(airportRepository.getReferenceById(flightRequest.airportDestinationId()));
flight.setAirline(airlineRepository.getReferenceById(flightRequest.airlineId()));
flight.setAirplane(airplaneRepository.getReferenceById(flightRequest.airplaneId()));
// 设置 Flight 的其他属性
flight.setFlightNumber(flightRequest.flightNumber());
flight.setDepartureTime(flightRequest.departureTime());
flight.setArrivalTime(flightRequest.arrivalTime());
flight.setDuration(flightRequest.duration());
flight.setPassengers(flightRequest.passengers());
return flightRepository.save(flight);
}
注意事项:
- getReferenceById 适用于您确定相关实体的存在,或者不在乎它是否存在(JPA 需要时会抛出异常场景。
- 若关联实体不存在,getReferenceById 在第一次访问其非ID属性时,返回的代理对象将被抛出 jakarta.persistence.EntityNotFoundException。因此,如果业务逻辑要求在保存前验证所有相关实体,findById 配合 orElseThrow 这仍然是一种更安全的做法。
在 Spring Boot 中处理 ManyToOne 建议使用以下策略创建和更新相关实体:
- 使用 DTOs 作为 API 输入/输出: 隔离模型与外界接口,提高灵活性和安全性。对于相关实体,DTO 只需包含其 ID。
- 服务层负责 DTO 实体映射:实体映射: 服务层的依据 DTO 中的 ID 对相关实体进行搜索和设置,确保领域模型的完整性。
-
合理选择 findById 或 getReferenceById:
- 使用时,需要验证关联实体是否存在,或者需要访问关联实体的其他属性 findById。
- 使用时只需设置外部关联,不关心或确保关联实体的存在 getReferenceById 避免不必要的数据库查询,提高性能。
- 完善错误处理: 对于关联实体不存在的情况,及时抛出明显的业务异常,提高系统的健康度。
- 事务管理: 确保服务层方法被接受 @Transactional 注释,以确保数据库操作的原子性和一致性。
通过遵循这些实践,您可以有效地管理它们 Spring Boot 应用中的 ManyToOne 关系使代码更清晰、更强大,性能更好。
以上是Spring Boot 中高效处理 ManyToOne 更多关于图灵教育的其他相关文章,请关注相关实体更新和创建的详细信息!
相关标签:
java ai proxy 区别 Java spring spring boot 构造函数 select 整型 字符串 接口 对象 数据库 性能优化