R – NHibernate – Multiple Database Mappings in 1 Class


Sorry if this seems a little crazy but ive been messing around with NHibernate for a while and have come accross a scenario that may not be possible to solve with NHibernate…

I have 1 database that contains a load of static data, imagine it like a huge product lookup database, just to point out this is an example scenario, my actual one is a bit more complex but similar principle to this… It is hosted on a completely different box so i cant do "database2.table1.somecolumn" which i noticed as a possible way round the issue if the 2 DBs were in the same box and server.

Anyway i also have another DB which contains data relating to users, so imagine a user has bought a load of stuff from Generic Website A, you have a list of IDs pertaining to what they have bought and an amount of how many they bought as well as some other information, but the actual data relating to the product is stored in the other database…

So if you imagine you want to combine this data into a PreviousPurchasedProduct model which contained all the information from the 1st database and the additional data from the 2nd db you would have to do a query similar to this: (if they were all on one box)

SELECT db1.products., db2.purchases.
FROM db2.purchases
INNER JOIN db1.products ON db2.purchases.product_id = db1.products.id
WHERE db2.purchases.user_id = XXX;

Now first of all is it possible to map this sort of thing up even though they are in seperate DB hosts, im guessing not and if thats the case can you achieve this flexibility via a child class. So having a product class that purely works off db1 and a derived class that takes the purchases info that only works from db2.

Also is it possible to restrict the db1 portion of data from INSERT/UPDATE/DELETE statements, im pretty sure you can in the default mappings but as this would be outside of the per class scope im not sure what flexibility i have…

Thanks for reading my waffle 😀

Best Solution

I would recommend you first understand how to solve this problem without NHibernate. Once you have one or more clean solutions that work without NHibernate, come back and update your question to say something like "how do I represent this SQL in NHibernate?".

Querying across databases can quickly bring database vendor specific quirks into play and you never mention which database vendor(s) you are dealing with. If both databases are the same vendor, you may be able to link the databases somehow using database vendor specific techniques (but linking isn't necessarily a good solution, so you'll want to try to uncover alternatives as well).