1

I have an entity with @OneToOne mapped subentity:

@Entity @Table
public class BaseEntity {

    @Id
    private String key;

    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private InnerEntity inner;

}

@Entity @Table
public class InnerEntity {

    private String data;
}

It was working perfectly on persist and merge operations until I decided to fetch all records in a named query (SELECT e FROM BaseEntity e). Problems are that after calling it, Hibernate fetches all records from BaseEntity and then executes distinct queries for each InnerEntity. Because table is quite big it takes much time and takes much memory.

First, I started to investigate if getInner() is called anywhere in running code. Then I tried to change fetchType to EAGER to check if Hibernate it's going to fetch it all with one query. It didn't. Another try was to change mapping to @ManyToOne. Doing this I've added updatable/insertable=false to @JoinColumn annotation. Fetching started to work perfectly - one SELECT without any JOIN (I changed EAGER back to LAZY), but problems with updating begun. Hibernate expects InnerEntity to be persisted first, but there's no property with primary key. Of course I can do this and explicity persist InnerEntity calling setKey() first, but I would rather solve this without this.

Any ideas?

Patryk Dobrowolski
  • 1,447
  • 2
  • 13
  • 25
  • See related questions: http://stackoverflow.com/q/1444227/466738, http://stackoverflow.com/q/21499580/466738, http://stackoverflow.com/q/17987638/466738, http://stackoverflow.com/q/24757555/466738 – Adam Michalik Dec 22 '15 at 12:28
  • @AdamMichalik, thanks for links. I found this solution already, but it started new cascade type "no parent key" issue. Now it looks it's necessary to explicity persist both entities at DAO layer. – Patryk Dobrowolski Dec 22 '15 at 12:54

2 Answers2

1

If you want inner field to be loaded on demand and your relation is @OnToOneyou can try this

@OneToOne(fetch = FetchType.LAZY, optional = false)

Matrix Buster
  • 258
  • 2
  • 9
0

When using HQL hibernate doesn't consider the annotations, so you should tell it how to work. In your case you should right the HQL like this: SELECT e FROM BaseEntity as e left join fetch e.inner

Nebras
  • 596
  • 1
  • 7
  • 16