Entity relation isn't updated when referencing more than one field

15 Views Asked by At

I have a problem where my table users have:

@OneToMany(mappedBy = "id.utenti", cascade = {CascadeType.ALL}, orphanRemoval = true)
private List<UtentiCatenaRuoli> ruoliUtente = new ArrayList<>();

that is linked to a relation table with 3 foreign keys, user, role and section where role apply.

Using mapstruct i map DTO to Entity and vice-versa, for example creating an user works like that:

{
"nome": "test",
"ruoli": [ # Translate for roles
    {
        "1": "ANAGRAF" # Pair for section and role
    },
    {
        "1": "ASSEGNA"
    }
]
}

That works on create, no problems. The same code dosn't work when I try to update. I get the EntityByReference, pass it to mapstruct update method, use the same "qualifiedByName" used in create but hibernate dosn't fill the "user" field on relation. I'll try to explain more:

@Named("toUtenteRuoloCatenaList")
default List<UtentiCatenaRuoli> toUtenteRuoloCatenaList(List<Map.Entry<Long, String>> values,
                                                        @Context RuoliRepository ruoliRepository,
                                                        @Context CatenaComandoRepository catenaComandoRepository) {
    List<UtentiCatenaRuoli> utentiCatenaRuolis = new ArrayList<>();
    values.forEach(pair -> {
        UtentiCatenaRuoliPK utentiCatenaRuoliPK = new UtentiCatenaRuoliPK(catenaComandoRepository.getReferenceById(pair.getKey()), ruoliRepository.getReferenceById(pair.getValue()));
        UtentiCatenaRuoli utentiCatenaRuoli = new UtentiCatenaRuoli(utentiCatenaRuoliPK);
        utentiCatenaRuolis.add(utentiCatenaRuoli);
    });
    return utentiCatenaRuolis;
}

This is what my mapstruct function uses for conversion from DTO roles to Entity, utentiCatenaRuoliPK is missing the user reference id that hibernate fills alone on INSERT, same thing dosn't happend on UPDATE. Result: Update throw exception cause relation table user filed can't be null.

Why there is a different treatment for insert and update?

EDIT: I'm using something similiar with a relation table that have only 2 foreign keys and all works fine(user_ref get autofilled in both situations)

0

There are 0 best solutions below