views:

165

answers:

1

Hi,

Using hibernate 3.2.4.sp1 I have two entities User and ContactInfo

A User has a related ContactInfo, relation is unidirectional, i.e. ContactInfo has no idea about the user it belongs to (nor should it as it is reused in other relations)

The User entity has an entity listener preventing other users than the actual user itself to update it in the database. This works fine. The problem is that one user can update another users ContactInfo. I would like to include running the entity listener when a save on a ContactInfo is cascaded from a user, is that possible?

Current relationship

@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@Cascade( { org.hibernate.annotations.CascadeType.ALL,
        org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
@JoinColumn(name = "CONTACT_PERSON", nullable = false)
public ContactPerson getContactInfo() {
    return contactInfo;
}

public void setContactInfo(ContactPerson contactInfo) {
    this.contactInfo = contactInfo;
}

Current: entity listener:

public class UserListener extends EntityListener {

    @PreUpdate
    @PrePersist
    @PreRemove
    public void checkWriteAuthorization(User user) throws IllegalUserAccessException {
        //access rules here
    }
}

I guess what I'm looking for is something like "@PreCascadeChanges"

The actual store call is always on the entity User, and updates gets cascaded to ContactInfo

+1  A: 

I would like to include running the entity listener when a save on a ContactInfo is cascaded from a user, is that possible?

I don't think it is so you'll have to perform yours checks in the callbacks @PreUpdate, @PrePersist and @PreRemove like for the User. And if you want to check that an Entity "belongs" to some user, then I guess that you have to store this information somewhere. In your case, I don't understand why you can't make the User-->ContactInfo association bidirectional. Can you clarify?

Pascal Thivent
Thanks. I dont want to make the association bi-directional because it is used for other entitities as well, e.g. a Company may have ContactPerson. Further more its a legacy system, so I want to avoid too much changes.I guess I need to do this check before persisting a user, thus making the listener superfluous.
Tomas