How to link four tables avoiding N-ary association - sql

I have those four tables in database :
USER
id
PERMISSION
id
OBJECT
id
CONTEXT
id
Now the problem is that I want to link them to say that a user has one or many permissions on one or many objects depending of a context.. It looks simple but I can't find a way to avoid n-ary association..
Hope someone will be kind enough helping me to solve this problem.
Thanks in advance.

You may be looking for something like a WEAK ENTITY
Basically, a weak entity is a database entity which doesn't make sense on its own, but needs one (or more) foreign keys to assume a proper identity and a meaning.
This means that you're moving from an N-ary relationship to N binary relationships.
One possible approach is this: let's say that we call this weak entity Rules
Rules(id, user_id, permission_id, object_id, context_id /*other columns*/);
each of your strong entities has a relationship with the rules table. I don't like a lot this approach, but for small datasets it may work pretty well.
As a general note, though, I suggest you to think a bit more about your database model: are you absolutely, positively sure that all these 4 entities have a so strong relationship together? For example, does "Context" has influence on users, objects and permissions or just on permissions? Does an object exists at the same time across multiple contexts, or it makes sense to bind an object inside a specific context (the same concept of a variable scope)?

Related

Is it ever a good idea to use NHibernate <join> from a partial many-to-many class?

I have a Shop table, a StaffRole table, and a ShopStaffRole table that serves as many-to-many, but with additional fields like IsRequired, etc.
Shop
ShopId
ShopName
ShopAddress
StaffRole
StaffRoleId
StaffRoleName
ShopStaffRole
ShopStaffRoleId
ShopId
StaffRoleId
IsRequired
So my choices seem to be a Shop class and a StaffRole class with NHibernate many-to-many mapping between them, but that won't map IsRequired well in my object model, so it makes sense to have a ShopStaffRole class as well, and one-to-many mappings between it and both Shop and StaffRole.
However, upon closer inspection, the StaffRole table has only an Id and a Name. Would it make sense to just use an NHibernate join to put the StaffRoleName directly into the ShopStaffRole class as a string, and do away with representing the StaffRole table as a class altogether?
I don't anticipate the StaffRoleName changing within this application, so I should be able to get away with a read-only mapping that prevents one ShopStaffRole from affecting others with the same StaffRoleName.
Does this make sense, or am I missing something? It feels like my object model is just aping my relational model, table by table.
As long as the redundancy isn't your biggest concern and you're not going to add any interface to manage roles later then you're good to go with the Join approach.
As it turns out, I sort of answered my own question. I can't say it's never a good idea to do this, but I feel now like there are so many potential gotchas that it's extremely unlikely to be worthwhile.
In my case, I realised that although this application wouldn't have to worry about StaffRole changing, there would be another table that found its way into the scope later on that referenced StaffRole as well, so if we ever wanted to look up a StaffRole of a Shop, then look up all the training material required by this StaffRole, then it would be a good way to have two-way accessors between StaffRole-ShopStaffRole, and StaffRole-TrainingStaffRole.

Unidirectional parent-child association not null

I have a class structure which is akin to a PurchaseOrder (parent) and PurchaseOrderLine (child) pattern, where the order lines will only be saved to the DB by saving the parent PurchaseOrder and will only ever be accessed via the parent too.
The DB has PurchaseOrderLine.PurchaseOrder set to not permit null values.
It seems from searching through the web that it is not possible to have a uni-directional association from PurchaseOrder via an IList property without having to have a property on the line pointing back when the child has a NOT NULL constraint for its PurchaseOrder column.
Is this really the case? It seems like one of the most basic things one would want to do with an ORM, I find it difficult to accept that a product as mature as NHibernate cannot handle such a basic scenario.
No it's not the case. Please see the example provided in the answer to this question: When to use inverse=false on NHibernate / Hibernate OneToMany relationships?
Well, it may be the case that you can't have unidirectional one-to-many relationship defined only on one side, but I'll argue with your statement that this is "one of the most basic things one would want to do with an ORM".
One of the most basic things would be to have unidirectional one-to-many defined only on many side - as it is natural for RDBM tables. And ORMs (despite the common misconception) are not intended (or able) to fully abstract domain model from underlying data source. Even if in some cases they can, the database side suffers from select N+1 problems or very ineffective queries.
Defining one-to-many at one side makes an impression that i.e. counting the collection is cheap. It is the case with plain object graphs, but not with NHibernate entities, as reading collection causes (at least one) call to the database. Eager fetching from one side is also not able to properly use database join mechanism in the way it's intended to be used (opposite to eager fetch from many side).
Even if I don't agree with a lot of arguments, I think it is useful to read some of the articles saying that "ORM is an anti-pattern", like this one. They helped me to leverage the way I think about ORMs and make me think about ORMs as a compromise between two not matching paradigms, but not the way to hide one behind another.
This can now be achieved in NH3 using the Not.KeyNullable()
this.HasMany(x => x.Actions)
.Access.BackingField()
.KeyColumn("[Application]")
.Not.KeyNullable()
.Cascade.AllDeleteOrphan();

How does one architect an entity in Core Data with a generic relationship?

Say you need to architect an app with an entity that can be associated with multiple other kinds of entities. For example, you have a Picture entity that can be associated with a Meal entity, a Person entity, a Boardroom entity, a Furniture entity, etc. I can think of a number of different ways to address this problem, but -- perhaps because I'm new to Core Data -- I'm not comfortable with any of them.
The most obvious approach that comes to mind is simply creating a relationship between Picture and each entity that supports associated pictures, but this seems sloppy since pictures will have multiple "null pointers."
Another possibility is creating a superentity -- Pictureable -- or something. Every entity that supports associated pictures would be a subentity of Pictureable, and Picture itself would have a one-to-one with Pictureable. I find this approach troubling because it can't be used more than once in the context of a project (since Core Data doesn't support multiple inheritance) AND the way Core Data seems to create one table for any given root entity -- assuming a SQLite backing -- has me afeard of grouping a whole bunch of disparate subentities under the umbrella of a common superentity (I realize that thinking along these lines may smack of premature optimization, so let me know if I'm being a ninny).
A third approach is to create a composite key for Picture that consists of a "type" and a "UID." Assuming every entity in my data model has a UID, I can use this key to derive an associated managed object from a Picture instance and vice versa. This approach worries me because it sounds like it might get slow when fetching en masse; it also doesn't feel native enough to me.
A fourth approach -- the one I'm leaning towards for the app I'm working on -- is creating subentities for both Picture and X (where X is either Meal, Person, Boardroom, etc.) and creating a one-to-one between both of those subentities. While this approach seems like the lesser of all evils, it still seems abstruse to my untrained eye, so I wonder if there's a better way.
Edit 1: In the last paragraph, I meant to say I'm leaning towards creating subentities just for Picture, not both Picture and X.
I think the best variations on this theme are (not necessarily in order):
Use separate entities for the pictures associated with Meal, Person, Boardroom, etc. Those entities might all have the same attributes, and they might in fact all be implemented using the same class. There's nothing wrong with that, and it makes it simple to have a bidirectional relationship between each kind of entity and the entity that stores its picture.
Make the picture an attribute of each of the entity types rather than a separate entity. This isn't a great plan with respect to efficiency if you're storing the actual picture data in the database, but it'd be fine if you store the image as a separate file and store the path to that file in an attribute. If the images or the number of records is small, it may not really be a problem even if you do store the image data in the database.
Use a single entity for all the pictures but omit the inverse relationship back to the associated entity. There's a helpful SO question that considers this, and the accepted answer links to the even more helpful Unidirectional Relationships section of the docs. This can be a nice solution to your problem if you don't need the picture->owner relationship, but you should understand the possible risk before you go down that road.
Give your picture entity separate relationships for each possible kind of owner, as you described in the first option you listed. If you'll need to be able to access all the pictures as a group and you need a relationship from the picture back to its owner, and if the number of possible owner entities is relatively small, this might be your best option even if it seems sloppy to have empty attributes.
As you noticed, when you use inheritance with your entities, all the sub-entities end up together in one big table. So, your fourth option (using sub-entities for each kind of picture) is similar under the hood to your first option.
Thinking more about this question, I'm inclined toward using entity inheritance to create subentities for the pictures associated with each type of owner entity. The Picture entity would store just the data that's associated with any picture. Each subentity, like MealPicture and PersonPicture, would add a relationship to it's own particular sort of owner. This way, you get bidirectional Meal<->MealPicture and Person<->PersonPicture relationships, and because each subentity inherits all the common Picture stuff you avoid the DRY violation that was bugging you. In short, you get most of the best parts of options 1 and 3 above. Under the hood, Core Data manages the pictures as in option 4 above, but in use each of the picture subentities only exposes a single relationship.
Just to expand a bit on Caleb's excellent summation...
I think it's important not to over emphasize the similarities between entities and classes. Both are abstractions that help define concrete objects but entities are very "lightweight" compared to classes. For one thing, entities don't have behaviors but just properties. For another, they exist purely to provide other concrete objects e.g. managed object context and persistent stores, a description of the data model so those concrete objects can piece everything together.
In fact, under the hood, there is no NSEntity class, there is only an NSEnitity***Description*** class. Entities are really just descriptions of how the objects in an object graph will fit together. As such, you really don't get all the overhead an inefficiency of multiplying classes when you multiply entities e.g. having a bunch of largely duplicate entities doesn't slow down the app, use more memory, interfere with method chains etc.
So, don't be afraid to use multiple seemingly redundant entities when that is the simplest solution. In Core Data, that is often the most elegant solution.
I am struggling with esactly this dilemma right now. I have many different entities in my model that can be "quantified". Say I have Apple, Pear, Farmer for all of those Entities, I need a AppleStack, PearStack, FarmerGroup, which are all just object+number. I need a generic approach to this because I want to support it in a model editor I am writing, so I decided I will define a ObjectValue abstract entity with attributes object, value. Then I will create child entities of ObjectValue and will subclass them and declare a valueEntity constant. this way I define it only once and I can write generic code that, for example, returns the possible values of the object relationship. Moreover if I need special attributes (and I actually do for a few of those) I can still add them in the child entities.

Django: Display many-to-many fields in the change list

Django doesn't support displaying of related objects from a many-to-many relation in the changelist for a good reason. It would result in a lot of database hits.
But sometimes it is inevitable and necessary to e.g. display an object's categories, which have a many-to-many relation to the object, in the changelist. Given that case, does anybody have some experiences/snippets etc. to speed this up a little (thinking of caching, custom sql queries...)? (I am aware of the fact that I can make a method that calls object.categories.all()... But this can really be a pain in the ass...).
Here you have to make a choice about denormalization in your model if you think that one more database hit per row in your changelist is unacceptable.
The question is how to store this ManyToMany relation ? Maybe you can go with a synced JSON serialized object in a CharField or a TextField to serialize the subset of fields you need (pk and name for instance).
But be careful with the side effects on performances when adding a potentially big column, the queryset's defer method is your friend.

Does NHibernate support mapping an abstract class to disparate tables using composite ids?

I have a complex, 3NF database being provided to me for a particular project. I would like to avoid using a class-per-table domain design. Rather, I would like to model my domain objects after how they are used from a conceptual business perspective.
The rub is how to properly persist this information. I know I can go the ADO route, but I'd like to take a stab at using NHibernate, having used it successfully on other projects with more flexible data stores.
So, I need to know if NHibernate will support the following scenario:
I have a conceptual object known as a ProjectStatus, which is comprised of a handful of date stamps for various activities along with some notes about the status. All of the data that comprises the ProjectStatus comes from 2 or more tables. There is no ProjectStatus table.
I know I can do a union-subclass in my NH mapping to get this to work, but...
One of the tables that holds the bulk of the information I need has a composite id (two PK fields that together make up the identity signature). I know NH supports composite ids as well, but how would I go about mapping my the union on the composite key? Do I need to specify a composite key underneath the union-subclass section?
The dba has refused to budge on her near-neurotic 3NF data model, so I'm stuck on that front. If I have to drop to ADO for ease/speed of development, so be it, but I'm hoping NH will rise above...
I gather that you have a base-class and two sub-classes that you want to map to two sub-class tables using the table-per-concrete-class mapping strategy. The two sub-class tables need to declare the same primary keys, and the primary keys need to be mapped in the base-class mapping. You have to declare the id or composite-id in the base-class mapping, so that you can ask NHibernate for an object of the base-class type with the given ID or composite ID. You can't declare them in the subclass-mapping, and you certainly can't declare them to be different for each subclass type (that's what declaring them in the subclass mapping would permit you to do), because from a strongly*-typed object-oriented perspective, that would be leaving the realm of sanity.
*Strong typing, to me, means that variables are statically typed (the type of each variable is known to and enforced by the compiler) and objects are strictly typed (the type of each object is known to and enforced by the runtime).