JPA Transactional method updates the column after already saving it

Viewed 225

Im saving an Object that is POSTed in REST Webservice , but Im trying to update some fields just before that. I have an A class that has a B as its property (no relationship, just a field - complexity due to this field being a separate JSON field/object). I am trying to update B's property before A is persisted which actually works just fine.. EXCEPT after it inserts the new class , it also updates the field. Something like that:

public class A {
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
Long id;

@Lob
@Convert(converter = BConverter.class)
B b_field;
}

public class B {
List<String> someVals;
List<Map<String, String>> amts;
}






@Converter
public class BConverter implements AttributeConverter<B, String> {
    
    private final static ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    public String convertToDatabaseColumn(B b) {
        try {
            return objectMapper.writeValueAsString(b);
        } catch (JsonProcessingException ex) {....
            return null;
        }
    }
    
    @SneakyThrows
    @Override
    public B convertToEntityAttribute(String bVal) {
        try {
            return objectMapper.readValue(bVal, B.class);
        } catch (IOException ex) {
            ......
            return null;
        }
    }
}

Here is the POST method for persisting:

@Override
@Transactional
public A saveA(A a){
  List<Map<String, String>> amts= new ArrayList<>();
  amts.add(....here goes some hashmap...);
  a.getB_field.setAmts(amts);
  return repository.save(a);
}

Fired queries are:

insert into A (id, b_field) -> here b_field already contains the added values from above
update A set b_field =? where id=?  -> same object that is already inserted. Basically useless

I can imagine it has to do with Transaction being committed, but dont understand why it doesnt get that there isnt any change. Any ideas? Thank you!!

1 Answers

Seems like I came closest to an answer myself, at least for now: it is the Map that breaks the flow. There are specialties when it comes to Maps and JPA, but still none of them worked for me till now in this case. Workaround: If I create a class with defined fields instead of dynamic map it works great.
UPDATE:
Inspired by a link from @jccampanero, Ive changed Map to JsonNode and am building a node dynamically with JsonNodeFactory. That works like a charm!

Related