tags:

views:

28

answers:

1

I have a PROPERTY table whose primary key is defined as (REF_1_ID, PROPERTY_ID, PROPERTY_IDX) , where PROPERTY_IDX ranges from 0 to n for the same values of (REF_1_ID, PROPERTY_ID) .

I would like to leave it to Hibernate to mange the value of PROPERTY_IDX, so that I can set it to null for new objects and have it populated on save.

What is the most straightforward way of achieving that?

+1  A: 

For the same values of (REF_1_ID, PROPERTY_ID)

You can retrieve how many Property Entity with the same (REF_1_ID, PROPERTY_ID) you have

Integer indexValue = (Integer)

session.createQuery("select count(*) from Property p where p.propertyId.rederenceId = :referenceId and p.propertyId.propertyId = :propertyId")
       .setParameter("referenceId", referenceId)
       .setParameter("propertyId", propertyId)
       .iterate()
       .next();

Then you set up

propertyId.setIndexValue(indexValue);

You can use an HibernateInterceptor to achieve this funcionality (onSave method) Keep in mind concurrency issues when dealing with this scenario

Or encapsulate as follows

@IdClass(PropertyId.class)
public class Property {

    private Integer referenceId;
    private Integer propertyId;
    private Integer indexValue;

    /**
      * You can use some repository instead
      *
      * setUp by using Either constructor Or setter injection
      */
    private Session session;

    public Property() {}
    public Property(Session session) {
        this.session = session;
    }

    @Id 
    public Integer getIndexValue() {
        if(indexValue != null)
            return indexValue;

        return (Integer)

            session.createQuery("select count(*) from Property p where p.propertyId.rederenceId = :referenceId and p.propertyId.propertyId = :propertyId")
                   .setParameter("referenceId", referenceId)
                   .setParameter("propertyId", propertyId)
                   .iterate()
                   .next();
    }

}
Arthur Ronald F D Garcia
Hoping I would find something simpler, but this seems to be the only way. Thanks!
Robert Munteanu