I have a parent-child relation, with just one child on Sql Server. The child contains fat blob data I won't load. The child is optional and it must depend on the lifecycle of the parent. So the foreign key on the child, point to the parent and is unique.
I can use the official example on Hibernate reference.
public class Phone
{
public virtual long Id { get; set; }
public virtual string Number { get; set; }
public virtual PhoneDetails Details { get; set; }
}
public class PhoneDetails
{
public virtual int Id { get; set; }
public virtual Phone Phone { get; set; }
public virtual string Provider { get; set; }
}
Phone details must depend on parent lifecycle on the database. I can use a one-to-one relation on sql with a unique foreign key on the child, or many-to-one relation with a simple foreign key (as in example) plus a unique constraint.
CREATE TABLE Phone (
id BIGINT IDENTITY PRIMARY KEY,
number VARCHAR(255)
)
CREATE TABLE PhoneDetails (
id BIGINT IDENTITY PRIMARY KEY,
phone_id BIGINT UNIQUE FOREIGN KEY REFERENCES dbo.Phone(id),
provider VARCHAR(255)
)
And this is fine i think:
So I have a Phone, this can live without details, and when I need I can add only one detail to complete my object with other details I don't want to load always.
How can I map these classes on NHibernate 5? It seems that i need to use HasOne, in a bidirectional way, but in that case I cannot use lazy load so every simple query on the Phone, will lead to a join and select of all the fields of the details.
I use the details table to store huge metadata that I must not need at 90% of time, but now everywhere I try to load a Phone, the query load also the huge details, this is really bad.
So in which way can I map this relation?
A parent, and a single child containing not useful fat data. In sql I think the structure is ok, because I don't want more children, and I want for them to live under the parent (so FK on child).
It is impossible that is not managed this type of relation, where am I wrong? database design? mapping?
This is the mapping I use:
<class name="Phone" table="Phone">
<id name="Id">
<generator class="native"/>
</id>
<property name="Number"/>
<one-to-one name="PhoneDetails" class="PhoneDetails"/>
</class>
<class name="PhoneDetails" table="PhoneDetails">
<id name="Id">
<generator class="native"/>
</id>
<property name="Provider" />
<many-to-one name="Phone" column="phone_id" unique="true"/>
</class>
I have also tried with the second options, to use a foreign\primary key on the relational model (so i removed the FK and used the same Id as PK\FK), with this mapping in the child:
<one-to-one name="Phone" class="Phone" constrained="true" />