【发布时间】:2020-07-16 16:01:14
【问题描述】:
我用 spring boot 启动一个项目,我使用一个有 6 个表的数据库。 这是一个 CRUD 应用程序。
所以,我有 5 个表的实体/dto/service/controller/repository 包。 (SQL 中有 6 个表)
现在,我想将实体 x 的表 x(SQL) 列上的一行更新为特定行的另一个实体 y。
在我看来,应该在create X的服务层做,但是怎么做呢?
我应该使用来自 2 个实体的数据创建 xyDTO 吗?我害怕这样做,它不会自动更新表 y。但是在创建 xyDTO 时。我不想要这个。
如何将特定 DTO x 的数据同时更新到另一个 DTO y(SQL 的第 6 表)
我在网上找不到类似的例子。谁能帮帮我?
我的代码:
@Entity
@Table(name = "repo")
public class Repo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
Long id;
@Column(name="stock")
private Long stock;
}
@Entity
@Table(name = "voucher")
public class Voucher {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "quantity")
private BigDecimal quantity;
@Column(name = "type")
private boolean type;
}
@Service
public class VoucherService{
@Override
public Voucher dtoToEntity(VoucherDTO dto) {
Voucher voucher = new Voucher();
voucher.setId(dto.getId());
voucher.setDescription(dto.getDescription());
List<VoucherProduct> voucherList = new ArrayList<>();
for (VoucherProductDTOMini inv : dto.getVoucherproducts()) {
VoucherProduct voucherL = voucherProductService.DTOtoEntity(inv);
voucherList.add(voucherL);
}
voucher.setVoucherproducts(voucherList);
return voucher;
}
@Override
public VoucherDTO createVoucher(VoucherDTO voucherDTO) {
Voucher voucher=new Voucher();
voucher=voucherRepository.save(voucher);
VoucherDTO voucherDTOnew=new VoucherDTO(voucher);
return voucherDTOnew;
}
}
我应该 检查我的凭证类型(真实),我应该在我的回购实体中添加 库存。
我可以通过哪种方式同时更新两个实体?
当我添加真正的凭证时,我应该在我的repo.stock 上添加voucher.quantity 的数据。
【问题讨论】:
-
请更好地澄清您的问题,因为很难理解您要做什么。如果您尝试更新外键列,请直接提及。此外,最好为您的实体提供您的代码,以便我们了解您的数据库中的关系。
-
基本上流程应该是这样的:获取你需要更新的实体 (让Hibernate处理所有的查询和延迟加载) -> 更改你想要的属性 -> 保存
-
非常感谢您的时间和提示。我在帖子中添加了一些代码,它可能会有所帮助。
标签: java spring spring-boot rest dto