Problem inserting object with ManyToOne JPA

0

I'll 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 an Item property annotated with ManyToOne, which I mapped to the database only by the id_item in my Main table.

When creating an instance of the main class in the web interface of my application, I select an instance of Item in a select that has only the id and name of the Item (Imagine that item has several other properties that I did not send to the application client). When selecting an Item to associate with the Principal, I assign a new instance of Item to the Principal and seto the Id of this item correctly in that instance. I then send Home to the server side of the application and persist using JPA with the Insert.

However, when I retrieve the Main list from the database, my new item does not have the Item description or the other properties it should have. It was saved correctly in the database, since if I make a select, it's there, in my line 1 of the main table has id_item = 3 for example referring to item 3 correctly registered in the Item table. But the JPA does not bring the other Item data. It is as if he had created a new cached instance of Item 3 containing only the id and uses this 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 get an error message when trying to save the Main containing the Item with just the Id, saying that the Item is unpinned. (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 Main associated with the Principal at the time of saving the Main. 2) Search the object Bank for the Item id by the Item instance that came from the client and associate this instance of the bank with the Principal before the new Principal persists to the bank.

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 a third option?

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

    
asked by anonymous 19.01.2016 / 12:27

1 answer

0

I do not think the first option is possible, it would be a lot of gabiarra, only if the object is in session. But I would do with the second option. You get what the user selected in the select field, searches the database for the object for which he selected and assigned the instance of Principal.

    
11.02.2016 / 19:03