如何仅使用@Id(代理对象)检索实体对象,检查它是否存在并将其分配给@ManyToOne 关联

How to retrieve an Entity Object just with @Id (Proxy object), check if it exists and assign it to a @ManyToOne association

我有一个实体 Product,它有很多字段和关联(大约 60 个)。
table ProductViewProduct 有 @ManyToOne(fetch = FetchType.LAZY) 关联.

是否有最佳方法来检索 Product 对象并将其分配给 ProductView?

  1. 如果使用 JPA findById(productId) 或 JPQL/EntityManager 选择-> 它将检索所有产品字段和关联

    Product product = productRepository.findById(productId); ProductView productView = new ProductView(product); save(productView);

  2. 如果使用 JPA getOne -> 它解决了问题,但如果 Product 不存在,Proxy 可能会抛出错误。而且这个错误无法处理,因为它发生在运行时。

    Product product = productRepository.getOne(productId); ProductView productView = new ProductView(product); save(productView);

  3. 如果使用 DTO 或引用相同产品的接口 Table -> 我们只会得到一个带有 Id 字段的对象,但需要添加更多进程(我不熟悉)

  4. 从 ProductView 中删除外键 table (@ManyToOne -> @Column) 并简单地分配 productIds。但是这样一来,table之间就没有逻辑联系了。

ProductView DB

开发人员通常如何避免这个问题?

我不明白这是什么问题。只需使用 getOne 方法,并在方法的末尾使用 flush ,这将抛出您可以处理的约束违规异常。这是要走的路。