Hibernate lazy-load transient fields

1.6k views Asked by At

I expect that this is an unusual use-case.

Say I have a entity class Foo:

@Entity
public class Foo {
    @Id
    private Long id;

    private String bar;

    @Transient
    private long bazz;

    ...
}

I also have an Interceptor defined such that Foo.bazz is initialized when instances of Foo are read from the database:

public class MyInterceptor extends EmptyInterceptor {
    ...

    @Override
    public boolean onLoad(
        Object entity,
        Serializable id,
        Object[] state,
        String[] propertyNames,
        Type[] types) {

        if(entity instanceof Foo) {
            Foo foo = (Foo)entity;

            long bazzValue = ... // some very heavyweight code

            foo.setBazz(bazzValue);
        }

        return false;
    }
    ...
}

So far, so good. But not all code paths will need the value of every Foo instance's bazz field. This means that the heavyweight code to find a value for each and every instance of Foo is sometimes needlessly invoked.

How do I go about avoiding invoking the code to find a value for bazz unless Foo.getBazz() is actually invoked?

1

There are 1 answers

0
Adam Maass On

OK, upon reflection:

Use the interceptor to populate an object into the Foo instance. This object can do the lazy initialization without violating the separation of concerns.