Paul Adamson
Paul Adamson

Reputation: 2021

delete hibernate entity without (attempting to) delete association table (view) entry

Entity A and B have a many to many relationship using link table AtoB.

If Entity A is deleted, the related links are deleted by hibernate. So far so good.

My problem is that my link table is a view hiding a much more complicated relationship and works perfectly in this situation except when hiberate tries to delete the link rows from the view, causing the database to complain.

@Entity A...   

@ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "AtoB", 
    joinColumns = @JoinColumn(name = "A_ID"), 
    inverseJoinColumns = @JoinColumn(name = "B_ID"))
 public Set<A> getASet() {
     return ASet;
 }

Is there a way to get hibernate to not delete the link rows? I haven't found any cascade options or the ability to use updateable=false etc on an association.

Upvotes: 1

Views: 1825

Answers (3)

Anonymous
Anonymous

Reputation: 66

I encountered this issue and the following worked for me:

@ManyToMany
@JoinTable(name = "V_LoanSecuredUser",
            joinColumns = @JoinColumn(name = "loanAdditionalInfo_id", updatable = false),
            inverseJoinColumns = @JoinColumn(name = "userAuthentication_Id", updatable = false))
@Persister(impl = ReadOnlyCollectionPersister.class)
@Immutable
public class ReadOnlyCollectionPersister extends BasicCollectionPersister {
    public ReadOnlyCollectionPersister(Collection collection,
            CacheConcurrencyStrategy cache, Configuration cfg,
            SessionFactoryImplementor factory) throws MappingException,
            CacheException {
        super(collection, cache, cfg, factory);
    }

    @Override
    protected boolean isRowDeleteEnabled() {
        return false;
    }

    @Override
    protected boolean isRowInsertEnabled() {
        return false;
    }
}

Upvotes: 5

candiru
candiru

Reputation: 4542

Try this:

@ManyToMany(
    fetch = FetchType.LAZY,
    cascade = { CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH })
...

See JPA Annotations for cascade types.

Upvotes: 3

matt b
matt b

Reputation: 140041

It sounds like you might be using the "link table" design incorrectly, if you want to model this as a ManyToMany relationship. You might want to look at breaking the extra items stored in this table into a separate table or storage.

Upvotes: 0

Related Questions