What is the best practice regarding one type of sleep mode

I think this is a common scenario. Say I have one, many hibernation displays: Category has many Items


Category:

 @OneToMany( cascade = {CascadeType.ALL},fetch = FetchType.LAZY) @JoinColumn(name="category_id") @Cascade( value = org.hibernate.annotations.CascadeType.DELETE_ORPHAN ) private List<Item> items; 

Item:

 @ManyToOne(targetEntity=Category.class,fetch=FetchType.EAGER) @JoinColumn(name="category_id",insertable=false,updatable=false) private Category category; 

Everything works perfectly. I use Category to fully manage the Item life cycle. But, when I write the code for updating Category , first I get Category from the database. Then pass it to the user interface. The user will fill in the changed values โ€‹โ€‹for the Category and go back. This is where the problem arises: because I only pass Category information, not Items , so the Items collection will be empty. When I call saveOrUpdate , it will clear all associations.

Any suggestion on what is best solved? I think the advantage of the Category Management of Items is that it is easy to maintain the order of Items and not be confused bi-directly.

But what about the situation you just want to update Category ? Download it first and merge?

+4
source share
1 answer

For your problem, if we see from a high level, without going into the code, I see that the problem is not in the sleep mode configuration, but in the way you process objects. I suggest you change the way you process your objects below,

1) You did not mention how you retrieve the Category object before passing it to the user interface. Therefore, if you use an object of the Category category using the get load method, you can simply create a separate initialization method that can load a collection of items by simply calling the getter method. Using the getter method, a small loaded collection of elements will be loaded, and then you can transfer it to the user interface. The user simply changes the category so that the elements remain as they are. Then after that you can save this entity, so the elements will remain as they are.

2) If you do not want to load a collection of elements before moving on to the user interface, you can simply select a category object without loading a collection of elements. Pass it to the user interface. As soon as the user modifies and transfers it back, instead of saving it directly, I suggest you first get the object of the new category for this category_id and get its elements loaded by calling getters, and then fill in the changed values โ€‹โ€‹from the category of returned user interfaces to this last selected category. Now you can save this merged object so that your collection of elements is safe.

+1
source

Source: https://habr.com/ru/post/1310326/


All Articles