Matt DeKrey
Matt DeKrey

Reputation: 11942

NHibernate map a property to a column in another table

I'm brand new to NHibernate - it worked great until I tried to apply it to one of the more common constructs we use in the Oracle 10g database at work.

I want to have a domain object as follows:

public class SentEmailHistory
{
    public virtual int Id { get; set; }
    public virtual string EmailAddress { get; set; }
    ...
}

The database I'm working with actually looks like the following:

SEND_EMAIL_HIST
================
SEND_EMAIL_HIST_ID (PK)
EMAIL_ADDR_ID (FK to EMAIL_ADDR)
...

EMAIL_ADDR
============
EMAIL_ADDR_ID (PK)
EMAIL_ADDR (AK1)

I don't want to have to alter my code any way just because the database split out an additional table where my code did not; I don't believe an "email address" justifies another domain entity.

If possible, I'd prefer to only update my hibernate mappings. Failing that, are there any non-obtrusive updates that can be made to the database?

Update

From what I've seen, the join syntax won't really support what I'm doing, especially when using existing email addresses that should be found in the EMAIL_ADDR table I described above. Can I provide raw insert/update queries to NHibernate? Or perhaps is an updatable view the only way to go?

Upvotes: 0

Views: 3077

Answers (2)

Matt DeKrey
Matt DeKrey

Reputation: 11942

After struggling for this for several weeks, I feel I've safely established that this is not possible in NHibernate. I've decided to either rewrite my classes or providing a one-off mapping wrapper to handle the requests.

If someone else comes up with a solution, please let me know.

Upvotes: 0

I82Much
I82Much

Reputation: 27326

Yes that's supported by the use of the "join" element. See http://ayende.com/blog/3961/nhibernate-mapping-join for more. It would probably look something like the following:

<class name="SentEmailHistory"
 table="SEND_EMAIL_HIST">

<id name="Id">
    <generator class="identity"/>
</id>
<join table="EMAIL_ADDR">
    <key column="EMAIL_ADDR_ID"/>
    <property name="EMAIL_ADDR"/>
</join>
</class>

The piece I'm not sure about is how you ensure a foreign key constraint between the PK ID of the SEND_EMAIL_HIST table and that of the EMAIL_ADDR column. In my xml above you'd end up with two IDs for one SentEmailHistory object, I think.

I'm sure a Hibernate expert can tell you more but Hibernate is pretty flexible in how it allows you to adopt to existing table structures. This StackOverflow question might also help.

Upvotes: 1

Related Questions