24 February, 2016

Viewing fake composites, or compositing fake views

Using Hibernate to retrieve data from a database view that contains a join can be tricky, as Hibernate expects there to be a unique primary key. The trick is to fake a composite key using the @Embeddable annotation in a PK model class that contains the properties/@Column references chosen for the composite key, and a the @EmbeddedId annotation in the main model class to include the PK class as the id property.

There's lots of documentation in cyberspace on the syntax for that, but there's one piece that almost all of them miss, and that is how you actually reference the properties that are defined in the @Embeddable compound key class.

First, do not duplicate the properties in both models; they should only occur in the PK model. The PK class is defined as a property of the main model class, so the reference is model.id.property for each element of the CK, instead of model.property.

I created accessors in the main model for the key properties that test that there is an instance of the PK model defined, primarily for testing. Example:

    public String getFirstName() {
        if ( null == this.id ) {
            return null;
        }
        return this.id.getFirstName();
    }

    public void setFirstName(String firstName) {
        if ( null == this.id ) {
            this.id = new ErmsDocOrgPrsnDetailPK();
        }
        this.id.setFirstName( firstName );
    }

It remains to be seen whether those will actually be needed.

No comments:

Post a Comment