Skip to content
Advertisement

Spring Jackson deserialize object with reference to existing object by Id

I have three entity classes of the following:

Shipments Entity:

JavaScript

Shipment Details Entity:

JavaScript

Product Entity:

JavaScript

I am receiving JSONs through a rest API. The problem is I do not know how to deserialize a new Shipment with shipmentDetails that have relationships to already existing objects just by ID. I know you can simply deserialize with the objectmapper, but that requires all the fields of product to be in each shipmentDetail. How do i instantiate with just the productID?

Sample JSON received

JavaScript

Currently my rest endpoint would then receive the JSON, and do this:

JavaScript

what i want to do is:

JavaScript

I tried this solution to no. avail: Deserialize with Jackson with reference to an existing object

How do I make the product entity search for an existing product instead of trying to create a new product. The hacky extremely inefficient workaround I have been using is to traverse the json array, and for every productId find the product using the productRepository, and then set the shipmentDetail with the product one by one. Im not sure if this is best practice as im self learning spring.

So in pseudocode what im trying to do would be:

  1. Receive JSON
  2. Instantiate Shipment entity
  3. Instantiate an array of shipmentDetail entities For each shipmentDetail: 1. Find product with given productId 2. Instantiate shipmentDetail with product and shipment

Code has been significantly simplified to better showcase the problem,

Advertisement

Answer

You have a bottleneck in your code in this part:

JavaScript

Because you are making a query for each productId, and it will perform badly with large number of products. Ignoring that, I will recommend this aproach.

  1. Build your own deserializer (see this):

    JavaScript
  2. Add the deserializer to your Shipment class:

    JavaScript
  3. Deserialize the string:

    JavaScript
  4. At this point, you are only converting the Json into classes, so we need to persist the data.

    JavaScript

I know you want to reduce the code in the test method, but I DO NOT RECOMMEND to combine the Json deserialize with the persistence layer. But if you want to follow that path, you could move the productRepository.findById(productId) into the ShipmentDeserializer class like this:

JavaScript

But if you want to do that, you need to inject the repository into the deserializer (see this).

Advertisement