A non-standard many-to-many relationship in NHibernate - 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.

Related

SQL Database Design ERD - Empty entity because of different function

As you can see below, the User is able to make a Call, the Operator will log it, writing the time (error on my part, Column2), his own ID and the ID of the caller. The Operator is also able to create a Solution, by generating a Solution ID and describing the solution.
Note that nothing differentiate the User from the Operator in terms of attributes. Indeed they both inherit their ID from the Person entity.
So I have two questions.
First, as you can see, the Call entity has two attributes which are the same column (ID for User and Operator), but will always represent two different people (i.e. a User will never be an Operator). Is this the correct notation for such a thing?
Secondly, I am not sure about having User and Operator as separate entities because no attribute distinguish them from one another, only their ability to do something or not (User can't create a solution). This would mean that they don't have attributes apart from the ones they inherit. Is this correct or should the two entities be merged under the Personentity?
Thanks in advance.
It's valid to create subtypes with distinct relationships and/or constraints, even if they have no distinct attributes. You'll be able to use referential integrity to ensure that Operator IDs and User IDs don't get mixed up in the Call table, and it's possible to enforce mutual exclusion between the IDs in the User and Operator tables.
As far as notation is concerned, I would show the ID in the User and Operator tables, and use Crow's foot lines to represent the FK constraints between the tables. If I wanted to make the subtyping explicit, I would rather show that on an EER diagram using Chen's notation than on a table diagram.

Is it possible to establish an association in Doctrine2 without target entity at hand?

There is a ManyToOne association defined between entities Pattern and Category (Pattern is an owning side of the relation). Category has many patterns, pattern belongs to one category. So there is a field Pattern.category with #ManyToOne Doctrine annotation.
Now, in my scenario I have the id of the Category entity (posted from form) that I want assign to Pattern.category field of the newly created Pattern (which will be persisted), but I don't want to load this Category entity - I don't need it, I just want to create a Pattern entity, assign it to a Category (which id I have), and persist it. It seems strange to me, that I have to load the Category entity just to establish the connection, when all I really need is just an id, which I already have.
Maybe it smells like using relational database concepts with ORM, but it seems completely pointless to load this entity just to establish connection, when I know id of that target entity.
I am new to Doctrine btw.
You can use Reference Proxy:
$category = $em->getReference('Category', $id);
$pattern->setCategory($category);

ORM and many-to-many relationships

This is more or less a general question and not about any specific ORM or language in particular: this question comes up regardless of your ORM preference.
When mapping a many-to-many relationship it is possible to obscure the intermediary table or to make the intermediary table a part of your model. In the case that the intermediary table has valuable data beyond the relationship, how do you handle the mapping?
Consider the following tables:
CaseWorker (id, first_name, last_name)
CaseWorkerCases (case_worker_id, case_id, date_opened, date_closed)
Case (id, client_id, field_a, field_b)
As a programmer I would really rather be able to do:
CaseWorker.Cases
than
CaseWorker.CaseWorkerCases.Cases
On the one hand, the table CaseWorkerCases contains useful data and hiding the intermediary table makes accessing that data less than convenient. On the other, having to navigate through the intermediary table makes the common task of accessing Cases seem awkward.
I supose one solution could be to expose the intermediate table in the model and then give the CaseWork object a wrapper property could work. Something like:
public IEnumerable<Case> Cases
{
get{return (from caseWorkerCase in this.CaseWorkerCases
select caseWorkerCase.Case);}
}
But that also seems wrong.
I regard many-to-many mappings as just a notational abbreviation for two one-to-many mappings with the intermediate table, as you call it, enabling simplification of the relationships. It only works where the relationships do not have attributes of their own. However, as understanding of the particular domain improves, I usually find that many-to-many mappings usually need to be broken down to allow attributes to be attached. So my usual approach these days is to always simply use one-to-many mappings to start with.
I don't think your workaround is wrong. The complexities of these models have to be coded somewhere.
I have a blog post about this exact topic: Many-to-many relationships with properties

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?

NHibernate - how to enforce uniquenes?

My scenario is as follows:
I have some objects (Messages) that can be tagged
So I have a Tag entity and many-to-many relationship
The above is done and working
Now, when tagging, I'd like to save new tags only if they don't exist (where existence is checked by tag title)
if the tag already exists, I'd like it to be recognized and attached to my object instead of a new one
What is the easiest/cleanest way to do it?
BTW, for some reasons I'd like to use artificial primary key (numeric Id) for my Tag entity.
Thanks!
You have a many-to-many relationship that you can express in your business classes and map with NHibernate. The structure of the linking table that resolves the many-to-many relationship will prevent an object from being linked to the same tag more than once.
The only way to enforce the rule in your question is through code. The sequence of tasks would be something like:
Parse user entered tag list into individual tags
Loop through tags ...
a. If a tag exists then add it to the object's tags collection
b. Else create a new tag and add it to the object's tag collection
Persist object
You will need to add logic to look for existing tags taking into account spelling mistakes, capitalization, and alternate usage. For example you don't want to have tags that mean they same thing but do are not equal strings, such as "ASPNET" or "ASP.NET" or "asp.net". The quality of your tag list will depend on how robust the code that checks for existing tags is.
Just to clarify - a Tag can be pinned on many Objects, and an Object can have many Tags. That's what a many-to-many relationship means to me. Is that how you mean it?
When you do this in SQL, you have tables named TAG and OBJECT and a join table named TAG_OBJECT that contains two columns, one for each primary key in the other tables. The primary key in the TAG_OBJECT join table is the pair (TAG_ID, OBJECT_ID). That guarantees a unique pairing for each row.
If you're using Hibernate, you just add a list or collection of Objects as a private data member to your Tag class, and a list or collection of Tags as a private data member to your Object class.
I think Hibernate will handle your "only if it doesn't exist", as long as you write a good method to determine "deep equality" between two instances of Tag.
You should also add a unique constraint to the tag title attribute. Here's an example that doesn't quite fit your needs, because it's Java and XML, but perhaps that hint will be enough to tell you where to look for NHibernate:
<element column="serialNumber" type="long" not-null="true" unique="true"/>
For your case, the column will be the tag title, type is string, and the other flags remain as they are in the example.