Problem inserting object with Manytoone JPA

Asked

Viewed 308 times

1

I will try to exemplify my problem with simpler classes than in my application:

I have for example the Main class and an Item class. In Main, I have a property of type Item annotated with Manytoone, which I mapped in the bank only by id_item in my Main table.

When creating an instance of the main class in the web interface of my application, I select an Item instance in a "select" that has only the id and name of the Item (Imagine which item has several other properties that I have not sent to the application client). When selecting an Item to associate to Main, I assign a new Item instance to Main and I set the Id of this item correctly at that instance. Then Main upload to the server side of the application and persist using JPA with Insert.

However, when retrieving the Core list from the bank, my new item does not have the Item description nor the other properties it should have. It was recorded all correctly in the database, since if I do a select, it is there, in my row 1 of the main table has id_item = 3 for example referring to item 3 correctly registered in the Item table. But JPA doesn’t bring the other item data. It’s as if he created a new cached instance of Item 3 containing only the id and uses it in the Main listing.

Then I tried to solve this problem by adding Cascade=Cascadetype.ALL in the Manytoone annotation of the Item in the Main class. However, in doing so, I have an error message when trying to save the Main containing the Item with only Id, saying that the Item is untied. (java.sql.Sqlexception: javax.persistence.Persistenceexception: org.hibernate.Persistentobjectexception: Detached Entity passed to persist:package.Item)

I can imagine 2 solutions to the problem: 1) Pass the entire Item object to the application client and return it to the entire Main associated object at the time of Save Main. 2) Search the database for the Item object by the id of the Item instance that came from the client and associate this instance of the database to the Main before persisting the new Main to the database.

I imagine that both should work, although not tested, but the first solution, generates additional traffic on the network, and the second, extra access to the bank.

Is there any third option?

If my explanation is not clear enough with the explanation with the dummy classes, my application is on github in github.com/codigoalvo/lab-Rest and the classes in question are Transaction as Main and Category and Account as Item.

1 answer

0

I think it is not even possible the first option, it would be a lot of gabiarra, only if the object is in the session. But I would do with the second option. You take what the user has selected in the select, search in the database the object referring to the one he selected and attached to the Main instance.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.