In order to keep transfered data small I created two entities for my files in the database. The fileheader to keep some general informations about the files and the fileblob, including fileId and the blob. Often, I only need to ask for general fileinformations. If I now ask for a list of fileheaders, hibernate unfortunatelly selects the fileblob too (each one in a single select). So here is my example:
Extract from Fileh.class:
@OneToOne(mappedBy = "fileh", targetEntity = Fileblob.class, fetch = FetchType.LAZY)
@org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.LOCK })
private Fileblob fileblob;
Extract from selection:
Criteria createCriteria = persistentSession.createCriteria(Fileh.class);
List list = createCriteria.list();
ConsoleLog:
Hibernate:
select
this_.`ID` as ID1_78_0_,
this_.`CHDATE` as CHDATE2_78_0_,
this_.`CHUSER` as CHUSER9_78_0_,
this_.`CRDATE` as CRDATE3_78_0_,
this_.`CRUSER` as CRUSER10_78_0_,
this_.`EXTENSION` as EXTENSIO4_78_0_,
this_.`NAME` as NAME5_78_0_,
this_.`SIZE` as SIZE6_78_0_,
this_.`VALID_FROM` as VALID_FR7_78_0_,
this_.`VALID_TO` as VALID_TO8_78_0_
from
CORE.`FILEH` this_
Hibernate:
select
fileblob0_.`ID` as ID1_77_0_,
fileblob0_.`FILEBLOB` as FILEBLOB2_77_0_
from
CORE.`FILEBLOB` fileblob0_
where
fileblob0_.`ID`=?
Hibernate:
select
fileblob0_.`ID` as ID1_77_0_,
fileblob0_.`FILEBLOB` as FILEBLOB2_77_0_
from
CORE.`FILEBLOB` fileblob0_
where
fileblob0_.`ID`=? .....(and so on)
Am I wrong with my assumption, that fetch = FetchType.LAZY should be sufficient for my purpose?
Thanks in advance for your hints and suggestions. I just think I´m barking up the wrong tree...
Kind regards, Vincent
Edit: Started to dive into hibernate sourcecode. In DefaultLoadEventListener.proxyOrLoad(...)
hibernate decides weather to load as proxy or not. In my example following option is passed: LoadEventListener.INTERNAL_LOAD_NULLABLE
which results in accessing the database. Just don´t understand why yet....
Edit2: Problem solved: added optional = false
to OneToOne-annotation:
@OneToOne(mappedBy = "fileh", targetEntity = Fileblob.class, fetch = FetchType.LAZY, optional = false)
@org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.LOCK })
private Fileblob fileblob;