Thanks to all and especially Frido - I will change my opinion on Lord of Rings film :-))
Solution of my question looks like this:
TERMINOLOGY
base entity = InstrumentHistory
foreign entity = Instrument
Code:
package com.domainmodel;
/**
* @hibernate.class table="INSTRUMENT_HISTORY_TBL" proxy="com.domainmodel.InstrumentHistory"
* @jboss-net.xml-schema urn="MyApp:InstrumentHistory"
*/
public class InstrumentHistory implements java.io.Serializable {
public Long id;
public Long instrumentId;
public Instrument instrument;
// etc....
public void setId(Long id) {
this.id = id;
}
/**
* @hibernate.id
*/
public Long getId() {
return id;
}
public void setInstrumentId(Long instrumentId) {
this.instrumentId = instrumentId;
}
/**
* This is foreign key - I wold like map also this field
*
* @hibernate.property
*/
public Long getInstrumentId() {
return instrumentId;
}
public void setInstrument(Instrument instrument) {
/**
* If foreign entity is set, also foreign key
* in base entity is synchronized because
* only value from instrument.instrumentId is
* updated to database
*/
if (instrument != null) {
instrumentId = instrument.getInstrumentId();
}
this.instrument = instrument;
}
/**
* This is getter for foreign entity
*
* @hibernate.many-to-one column="instrumentId" class="com.domainmodel.Instrument" insert="false" update="false"
*/
public Instrument getInstrument() {
return instrument;
}
// etc....
}
With this class mapping:
* it is possible directly set instrumentId to Instrument object
* while foreign entity is set, also Instrument.instrumentId is set via code in setInstrument() - kind of synchronization
* also foreign keys in schema generation are generated right (one of these (foreign key or foreign entity) must be mapped as insert="false" update="false" )
* can be read object (optionally) without foreign entity and also with foreign entity (lazy loading - proxy="com.domainmodel.InstrumentHistory")
Examples of code.
Reading without loading of foreign entity - Example 1:
Code:
obj = session.load(InstrumentHistory.class, new Long(10));
Hibernate.initialize(obj);
session.close();
Reading without loading of foreign entity - Example 2:
Code:
try {
results = (List) session.find("from InstrumentHistory");
} catch (HibernateException he) {
he.printStackTrace();
} finally {
session.close();
}
Reading with loading of foreign entity - Example 3:
Code:
obj = session.load(InstrumentHistory.class, new Long(10));
Hibernate.initialize(obj);
Hibernate.initialize(obj.getInstrument());
session.close();