Java JPA 只为嵌套实体写入 ID
如何避免对数据库进行不必要的查询? 我有 LoadEntity 和两个嵌套实体 - CarrierEntity 和 DriverEntity。 Java类:
@Entity
public class LoadEntity {
...
@ManyToOne
@JoinColumn(name="carrier_id", nullable=false)
private CarrierEntity carrierEntity;
@ManyToOne
@JoinColumn(name="driver_id", nullable=false)
private DriverEntity driverEntity;
}
但是API向我发送了rierId和driverId。我做到了:
DriverEntity driverEntity = driverService.getDriverEntityById(request.getDriverId());
loadEntity.setDriverEntity(driverEntity);
loadRepository.save(loadEntity);
如何用JPA只写driverId?
How can I avoid unnecessary queries to the DB?
I have LoadEntity with two nested entity - CarrierEntity and DriverEntity. Java class:
@Entity
public class LoadEntity {
...
@ManyToOne
@JoinColumn(name="carrier_id", nullable=false)
private CarrierEntity carrierEntity;
@ManyToOne
@JoinColumn(name="driver_id", nullable=false)
private DriverEntity driverEntity;
}
But API send me carrierId and driverId. I make it:
DriverEntity driverEntity = driverService.getDriverEntityById(request.getDriverId());
loadEntity.setDriverEntity(driverEntity);
loadRepository.save(loadEntity);
How can I write only driverId with JPA?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
借助 Spring Data JPA,您始终可以依靠纯 SQL。
当然,这将回避 JPA 为您提供的所有伟大/烦人的逻辑。
这意味着您不会收到任何事件,并且内存中的实体可能与数据库不同步。
因此,如果您使用乐观锁定,您还可以增加版本列。
也就是说,您可以像这样更新一个字段:
如果您只是想避免加载
DriverEntity
,您也可以使用JpaRepository.getById
With Spring Data JPA you can always fall back on plain SQL.
Of course, this will side step all the great/annoying logic JPA gives you.
This means you won't get any events and the entities in memory might be out of sync with the database.
For this reason you might also increase the version column, if you are using optimistic locking.
That said you could update a sing field like this:
If you just want to avoid the loading of the
DriverEntity
you may also useJpaRepository.getById