Separate table for Value Objects on NHibernate - nhibernate

I'm new to DDD and NHibernate.
In my current project, I have an entity Person, that contains a value object, let's say Address. Today, this is fine. But maybe one day I will have a requirement that my value object (in this case Address), will have to become an entity.
Before trying to model this on a DDD-way, in a more data-centric approach, I had a table Person, with an Id, and another table Address, whose PK was actually an FK, it was the Id of a Person (ie, a one-to-one relationship).
I've been reading that when I map a Value Object as a Component, its value will get mapped as columns on my Entity table (so, I would not have the one-to-one relationship).
My idea was that, when needed, I would simply add a surrogate key to my Address table, and then it becomes an Entity.
How should I design this using NHibernate? Should I already make my Address object an Entity?
Sorry, I don't even know if my questions are clear, I'm really lost here.

In the system we are building, we put Value-Objects in separate tables. As far as I know, NHibernate requires that an id must added to the object, but we ignore this and treat the object as a Value-Object in the system. As you probably know, a Value-Object is an object that you don't need to track, so we simply overlook the id in the object. This makes us freer to model the database the way we want and model the domain model the way we want.

You can Join and make it a Component allowing nHibernate to map it as a proper value object instead of an entity.
This way you won't need any virtual properties nor an empty protected ctor (it can be private).
Join("PROPOSAL_PRODUCT", product =>
{
product.Schema(IsaSchema.PROPOSALOWN);
product.KeyColumn("PROPOSAL_ID");
product.Component(Reveal.Member<Proposal, Product>("_product"), proposalProduct =>
{
proposalProduct.Map...
});
});

Related

Should uniqueness be ignored when deciding if something is an Entity or Value Object?

Is uniqueness considered a persistence concern in DDD?
The reason I ask is because I have a Customer object in an order quoting context. e.g. an order is for a customer and the customer must pay a certain rate.
Technically, I won't allow a customer to have the same code or name as another. Which means if I have two Customer objects with the same code and name, they'll always be treated the same like a value object.
But instinctively, a Customer feels like an entity. Is the unique constraint throwing me off, or am I right to think it's a value object?
The order quoting context will also allow customers to be added/edited/removed from an admin page. Could the confusion be caused by this? Should admin pages be part of another context where Customer is an entity, and the order quoting context will use Customer as a value object?
This is an excellent question, and you partially answered it already, your Customer is an Entity in your bounded context of administration.
A good rule of thumb to decide whether or not an object is an entity is to think with the concept of identity. If your object require an identity which will stay the same as the time flies, even if the person's name or contact details can change then its likely an Entity.
However, with that concept defined, you can have a CustomerId, which is composed of the invariant from a business point of view, in your case the code and name.
This CustomerId is not a technical ID, its a business ID, and your entity's identity will be this ID. In the Order quoting bounded context, you can then reference your Customer using this same object (probably defined somewhere in a shared context, or by duplicating the code: its ok in DDD to duplicate some code to promote loose coupling).

A non-standard many-to-many relationship in NHibernate

I have two tables (Rule and Object) linked through a many-to-many relationship. A Rule may be associated with any number of Objects, or it may be associated with all Objects.
I would normally build this association with a link table where, the Object_ID column would be set to NULL if the associated Rule was to be associated with all Objects. Any value that won't actually reference a real Object will do.
This way, I could write an Select to find all Rules associated with an object like this:
SELECT * FROM Rule JOIN RuleObject_Link on Rule.ID = RuleObject_Link.RuleID WHERE RuleObject_Link.ObjectID = <the object ID> or RuleObject_Link.ObjectID IS NULL
The problem is that I am using NHibernate. I can't find a way to signify "all Objects" in the automated relationship/collection structure.
Is it possible to build a relationship like this using NHibernate's many-to-many relationship?
Or will I have to manually configure the link table and handle the connection myself?
It would be better to add a separate boolean field to Rule signifying that it applies universally to all Object objects (Object is a pretty bad classname by the way).
This really doesn't participate in the relationship mapping, and getting the entire list of rules for an object would require a query rather than being populated automatically from mappings, but I can't think of anything better right now.

Fluent Nhibernate and Dynamic Table Name

I've got a parent and child object. Depending on a value in the parent object changes the table for the child object. So for example if the parent object had a reference "01" then it will look in the following table "Child01" whereas if the reference was "02" then it would look in the table "Child02". All the child tables are the same as in number of columns/names/etc.
My question is that how can I tell Fluent Nhibernate or nhibernate which table to look at as each parent object is unique and can reference a number of different child tables?
I've looked at the IClassConvention in Fluent but this seems to only be called when the session is created rather than each time an object is created.
I found only two methods to do this.
Close and recreate the nhibernate session every time another dynamic table needs to be looked at. On creating the session use IClassConvention to dynamically calculate the name based on user data. I found this very intensive as its a large database and a costly operation to create the session every time.
Use POCO object for these tables with custom data access.
As statichippo stated I could use a basechild object and have multiple child object. Due to the database size and the number of dynamic table this wasn't really a valid option.
Neither of my two solutions I was particularly happy with but the POCO's seemed the best way for my problem.
NHibernate is intended to be an object relational mappers. It sounds like you're doing more of a scripting style and hoping to map your data instead of working in an OOP manner.
It sounds like you have the makings of an class hierarchy though. What it sounds like you're trying to create in your code (and then map accordingly) is a hierarchy of different kinds of children:
BaseChild
--> SmartChild
--> DumbChild
Each child is either smart or dumb, but since they all have a FirstName, LastName, Age, etc, they all are instances of the BaseChild class which defines these. The only differences might be that the SmartChild has an IQ and the DumbChild has a FavoriteFootballTeam (this is just an example, no offense to anyone of course ;).
NHibernate will let you map this sort of relationship in many ways. There could be 1 table that encompasses all classes or (what it sounds like you want in your case), one table per class.
Did I understand the issue/what you're looking for?

Should one include ID as a property on objects persisted to a database?

I am creating the model for a web application. The tables have ID fields as primary keys. My question is whether one should define ID as a property of the class?
I am divided on the issue because it is not clear to me whether I should treat the object as a representation of the table structure or whether I should regard the table as a means to persist the object.
If I take the former route then ID becomes a property because it is part of the structure of the database table, however if I take the latter approach then ID could be viewed as a peice of metadata belonging to the database which is not strictly a part of the objects model.
And then we arrive at the middle ground. While the ID is not really a part of the object I'm trying to model, I do realise that the the objects are retrieved from and persisted to the database, and that the ID of an object in the database is critical to many operations of the system so it might be advantageous to include it to ease interactions where an ID is used.
I'm a solo developer, so I'd really like some other, probably more experienced perspectives on the issue
Basically: yes.
All the persistence frameworks ive used (including Hibernate, Ibatis) do require the ID to be on the Object.
I understand your point about metadata, but an Object from a database should really derive its identity in the same way the database does - usually an int primary key. Then Object-level equality should be derived from that.
Sometimes you have primary keys that are composite, e.g first name and last name (don't ever do this!), in which cases the primary key doesn't become 'metadata' because it is part of the Object's identity.
I generally reserve the ID column of an object for the database. My opinion is that to use it for any 'customer-facing' purpose, (for example, use the primary key ID as a customer number) you will always shoot yourself in the foot later.
If you ever make changes to the existing data (instead of exclusively adding new data), you need the PK. Otherwise you don't know which record to change in the DB.
You should have the ID in the object. It is essential.
The easiest use case to give as an example is testing equality:
public bool Equals(Object a, Object b) { return {a.ID = b.ID}; }
Anything else is subject to errors, and you'll find that out when you start getting primary key violations or start overwriting existing data.
By counterargument:
Say you don't have the ID in the object. Once you change an object, and don't have it's ID from the database, how will you know which record to update?
At the same time, you should note that the operations I mention are really private to the object instance, so ID does not necessarily have to be a public property.
I include the ID as a property. Having a simple unique identifier for an object is often very handy regardless of whether the object is persisted in a database or not. It also makes your database queries much more simple.
I would say that the table is just a means to persist an object, but that doesn't mean the object can't have an ID.
I'm very much of the mindset that the table is a means to persist the object, but, even so, I always expose the IDs on my objects for two primary reasons:
The database ID is the most convenient way to uniquely identify an object, either within a class (if you're using a per-table serial/autonumber ID) or universally (if you're maintaining a separate "ID-to-class" mapping). In the context of web applications, it makes everything much simpler and more efficient if your forms are able to just specify <input type=hidden name=id value=12345> instead of having to provide multiple fields which collectively contain sufficient information to identify the target object (or, worse, use some scheme to concatenate enough identifying information into a single string, then break it back down when the form is submitted).
It needs to have an ID anyhow in order to maintain a sane database structure and there's no reason not to expose it.
Should the ID in the object read-only or not? In my mind it should be read-only as by definition the ID will never change (as it uniquely identifies a record in the database).
This creates a problem when you create a new object (ID not set yet), save it in the database through a stored procedure which returns the newly created ID then how do you store it back in the object if the ID property is read-only?
Example:
Employee employee = new Employee();
employee.FirstName="John";
employee.LastName="Smith";
EmployeeDAL.Save(employee);
How does the Save method (which actually connects to the database to save the new employee) update the EmployeeId property in the Employee object if this property is read-only (which should be as the EmployeeId will never ever change once it's created).

How would you model a "default child" flag with an ORM?

I'm using an ORM (SQLAlchemy, but my question is quite implementation-agnostic) to model a many-to-many relationship between a parent class and its children.. I was wondering, what would be a simple way to express the concept "one of the children is the default/main one"?
For example, I'd need to persist the following:
This Person instance has Address X and Y, the main one is Y.
I saw this implemented using a "middle" class like "PersonAddressRelation" that would contain "Person", "Address" and the "main" flag, but I think it looks a bit cumbersome.. Is there a better way?
The simplest way would be to have a join table, PersonAddressRelation, and also a DefaultAddress column on the Person table that keys to the Address table.
A couple of remarks.
M:N relationships don't specify 'parent' and 'child', as there's no parent nor a child: there are simply two entities having an m:n relationship via a 3rd entity (the intermediate entity).
'Address' is in general not a valid entity type, as semantically it has no identity, similar to a 'name' has no identity (first name, last name). You'll see this when you look at re-using an entity instance of type Address: you won't do that in general. (though you will re-use a Customer entity instance for example, when the customer has multiple orders)
You want to specify an attribute on the M:N relationship (default), as it belongs there. This means that the relationship itself forms an entity (which is the intermediate entity, often it has just two FK fields forming the PK). This is called an 'objectified relationship', as the relationship itself is seen as an entity. Other examples of this are Employee m:n Department and you want to specify the StartDate an employee started for a department the employee works for.
So in general: create the intermediate entity, as it in general should be there, and add the attribute there. In this particular case with Address, be really sure you are re-using Address instances among related entities (Person). If not, merge Address with Person OR if a person can have multiple addresses, create a simple 1:n relationship between Person - Address, to normalize it out, though don't be afraid to merge address data into the entity it is related to, as often address data is really not re-used (so your m:n relationship is really not there: there's no Address instance which is related to multiple person instances.