3

I mapped this entity in Hibernate 5

class A {
    private String code;
    private B child;

    @LazyToOne(LazyToOneOption.PROXY)
    @ManyToOne(fetch=FetchType.LAZY)
    @NotFound(action=NotFoundAction.IGNORE)
    @JoinColumns({...})
    public B getChild() { ... }
}

And my query to load only A is:

from A where a.code like :q

With this configuration Hibernate makes a select on A and on B entities. I don't want it to load B but only A

What am I missing?

4
  • Is that really the entire class? This technique only works if hibernate can generate a proxy for the class, but other contents of your class (like a nondefault constructor, or it being final) could prevent hibernate from generating a proxy. Commented Jun 29, 2016 at 10:59
  • This is all class. gist.github.com/stefanopulze/c921cf477c6713feee3f79e42a51fef6 Commented Jun 29, 2016 at 13:16
  • Consider using entity JPA 2.1 entity graphs: thoughts-on-java.org/jpa-21-entity-graph-part-1-named-entity Commented Jul 1, 2016 at 8:14
  • Do you really need the NotFound? My guess is that this is the cause of your problem: you're basically saying Hibernate: my schema is a mess, and although table A has a column containing the ID of a B, that B might not exist. So Hibernate needs to select from B to know if that B exists or not. Fix your data, add a foreign key constraint, remove the NotFound, and it shouldn't load from B anymore. Commented Jul 1, 2016 at 9:18

1 Answer 1

5

I had the same problem, which is caused by Hibernate ignoring the FetchType.LAZY, if NotFoundAction.IGNORE is defined.

After some googling I found a workaround: http://chekkal.blogspot.com/2012/09/hibernate-lazy-loading-and-notfound.html

public FieldType getField() {
    if(!Hibernate.isInitialized(field)) {
        try {
            Hibernate.initialize(field);
        }catch(EntityNotFoundException one) {
            field=null;
        }
    }
    return field;
}

In Hibernate 5.4.2 the exception has changed to EntityNotFoundException, but this workaround seems to work for me.

Sign up to request clarification or add additional context in comments.

2 Comments

Is this approach really faster than FetchType.EAGER and NotFoundAction.IGNORE?
Well, I don't think it's faster than FetchType.EAGER, when you access the field. But with the concept of lazy loading you can load data only when/if it is needed. Especially in big entity classes with several relationships, you might not want to load all relating objects by default, but only when required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.