Search code examples
springhibernateboot

How to use @ManyToMany when reading Entity but ignore it when saving Entity in Spring Boot


I want to use @ManyToMany Relationship when reading Entitiy in order to get all the children to display them.

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
    name               = "ENTITY_BUTTONS",
    joinColumns        = @JoinColumn(name = "ENTITY_ID"),
    inverseJoinColumns = @JoinColumn(name = "BUTTON_ID")
)
private List<Button2> entityButtons;

But when using the same Entity from another Endpoint, which is supposed to only update Entity Columns, I want @ManyToMany Relationship to be ignored. In other words when updating Entity, and this @ManyToMany Relationship is empty List, I don't want it to delete all the Records from the Junction Table.

This is because I have separate Entitiy that is used for the Junction Table and I will be updating it through that.

So something similar to updatable = false with @ManyToOne relationship as shown below

@ManyToOne(fetch = FetchType.LAZY)    
@JoinColumn(name = "ICON_ID", insertable = false, updatable = false)    
@OnDelete(action = OnDeleteAction.CASCADE)    
private Icon icon;

Solution

  • If your Column Entity is the owning side of the many-to-many relation changes to the Button-List will be reflected in the DB.

    You could just check for null manually and call Hibernate.initialize(yourColumn.getEntityButtons()) to manually re-attach the List before your update.