Search code examples
spring-boothibernateproxyentitymany-to-one

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


I have an entity Product which have many fields and associations (around 60).
And a table ProductView which has a @ManyToOne(fetch = FetchType.LAZY) association with Product.

Is there a optimal way to retrieve Product object and assign it to ProductView ?

  1. If its used JPA findById(productId) or JPQL/EntityManager selects-> It will retrieve all products fields and associations

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

  2. If its used JPA getOne -> It solves the problem but the Proxy can throw error if Product does not exists. And this error can not be handled because it happens at runtime.

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

  3. If a DTO is used or Interface which refers to the same Product Table -> We will get just an object with Id field, but a lot more processes will need to be added (Which I am not familiar with)

  4. Delete foreign keys from ProductView table (@ManyToOne -> @Column) and simple assign productIds. But in this way, there will be no logic connection between tables.

ProductView DB

How usually developers avoid this problem ?


Solution

  • I don't understand what the problem is. Just use getOne approach and at the end of your method, use flush which will throw the constraint violation exception that you can handle. This is the way to go.