Is entity an instance of class?
A class is a template for an object (among other things), and is a very general concept.
An entity has more semantic significance and is usually tied to a concept (possibly about a real object for example, an Employee or a Student or a Music Album) and is linked to business logic.
Entities are usually used to establish a mapping between an object and to a table in the database. Entities are also known as domain objects. Like I mentioned before, entities will be used in situations where there is business logic and as such it hold information about the system (or part of the system) that it is modeling.
To add one more point
Class is a syntactic i.e. A set or category of things having some property or attribute in common and differentiated from others by kind, type, or quality.
Entity is a semantic i.e. relating to meaning in language or logic. An entity is something that exists in itself, actually or potentially, concretely or abstractly, physically or not. It needs not be of material existence.
Object is a in-memory value referenced by identifier, it is an instance of a Class.
An entity usually refers to something, anything really, that has a unique and separate existence.
In software development this word is almost only used to denote that one instance is different from another instance and they are independent of each other.
A class, on the other hand, defines or contains the definition of an object. Once that object is constructed based on the definition, then you get your instance or object instance.
Short -- yes.
Entity is more a concept from real world.
Instance (alias is object) -- from programming world.
In programming world we also has an "entity" concept, but here it's more a child of an instance. So any entity is a child of instance. Also entity has it's links to other things but programming -- for example, as people said -- entity can have table in DB.
Instance can't have table in DB. As instance is always connected to class.
An object is an entity that has state, behavior, and identity. The structure and
behavior of similar objects are defined in their common class. The terms instance
and object are interchangeable.
From Grady Booch book.
So we could say, that entity, object and class instance are interchangeable.
Entities
An entity is a lightweight persistence domain object. Typically an entity represents a table in a relational database, and each entity instance corresponds to a row in that table. The primary programming artifact of an entity is the entity class, although entities can use helper classes.
The persistent state of an entity is represented either through persistent fields or persistent properties. These fields or properties use object/relational mapping annotations to map the entities and entity relationships to the relational data in the underlying data store.
Entity classes have a stereotype of entity. An entity class is essentially an object wrapper for a database table. The attributes of an entity are transformed to columns on the database table. Entities can have various data maintenance operations such as read, insert, modify, remove, readmulti (read multi reads multiple records from a table based on a partial key).
Entities can have attributes, operations, dependencies, inherits relations, and aggregations. A set of rules is associated with each of these constructs.
Entity class rules
Entities must have at least one attribute. The exception is if the entity is a subclass of another entity, in which case the entity must have no attributes. Entities are not allowed to aggregate other classes.
Entity attributes
Entity attributes correspond to columns with the same name on their associated database table.
Entity operations
Entity operations can be divided into two categories as determined by their stereotype: database and non-database operations.
Entity outputs
Entity classes are transformed into classes with operations and no attributes. The attributes from the entity in the input meta-model are transformed into one or more structs.
Entity class options
The options available for entity classes are entity class abstracts, allow optimistic locking, audit fields, enable validation, last updated field, No Generated SQL, and replace superclass.
Optimistic locking for concurrency control
Using optimistic locking for concurrency control means that more than one user can access a record at a time, but only one of those users can commit changes to that record.
Table-level auditing
Use the Database table-level auditing option to enable table-level auditing.
Exit points
An exit point is a callback function that you write. It is executed at a predefined strategic point by the server.
Entity inheritance
Input meta-model entity classes can subclass other entity classes.
Last updated field
The last updated field is a field that you can add to database tables to contain extra information about the modification time of each record for reporting purposes.
Also you can check this link and this link for more information!
I copy from this paper, "Entity based Programming Paradigm", Nimit Singhania. University of Pennsylvania:
An entity is an abstract unit that represents a group of
nodes or sub-entities. It uses the services provided by its
sub-entities and collaboration between these sub-entities to
achieve its required goals. It has its own identity and appears
as a single unit to the external world just as in real
life a team or an organization is a whole unit and not just a
collection of individuals. A distributed system is essentially
a hierarchy of entities where each entity has a specific role
and provides specific services [...]
[...]The entity abstraction is very similar to an object in object
oriented programming. The key difference between an object
and an entity is that an entity is an active and a live
unit while an object is passive. An entity consists of live subentities
interacting with each other to provide a service and
can possibly interact with the other entities. Whereas, an
object consists of only static fields and properties that can be
queried and manipulated by the external world. But, many
insights from object oriented programming can be carried
over to this programming paradigm. We can have classes
and types of entities, where a class might provide specific
services and functionality to the rest of the system. Also,
we could define abstract entities which implement the core
structure and some basic protocols for interaction between
nodes and these could be extended further to realize the actual
entities. Similarly, we could define interfaces that define
a set of services. These interfaces could be implemented by
multiple entities with different guarantees and based on the
requirements, one of them could be chosen by the programmer
to provide the required service.
Related
I am reviewing my knowledge in object-oriented programming. Under the relationship between classes topic, I have encountered some relationships which are a bit ambiguous to me.
I know dependency "uses-a" and inheritance "is-a" but I'm a bit unfamiliar with Aggregation, Composition, Association and Direct Association; also, which of them is "has-a" relationship. Some use Aggregation interchangeably with Association.
What is Direct Association? Also, what is Composition? In UML diagrams, the arrows that represents them are different. I would be really thankful if you could clear these things out for me.
Please note that there are different interpretations of the "association" definitions. My views below are heavily based on what you would read in Oracle Certification books and study guides.
Temporary association
A usage inside a method, its signature or as a return value. It's not really a reference to a specific object.
Example: I park my Car in a Garage.
Composition association
A so-called "STRONG relationship": The instantiation of the linked object is often hard
coded inside the constructor of the object. It cannot be set from
outside the object. (Composition cannot be a many-to-many
relationship.)
Example: A House is composed of Stones.
Direct association
This is a "WEAK relationships". The objects can live independent and there are usually setters or other ways to inject the dependent objects.
Example: A Car can have Passengers.
Aggregation association
Very similar to a Direct association. It's also a "WEAK relationship" with independent objects. However here the associated objects are a crucial part of the containing object.
Example: A Car should have Tires.
Note: Both Direct associations and Aggregation associations are often generalized as "Associations". The difference is rather subtle.
The whole point of OOP is that your code replicates real world objects, making your code readable and maintainable.
1. Association
Association is: Class A uses Class B.
Example:
Employee uses Bus/train Services for transportation.
Computer uses keyboard as input device
And in In UML diagram Association is denoted by a normal arrow head.
2. Aggregation
Class A contains Class B, or Class A has an instance of Class B.
An aggregation is used when life of object is independent of container object. But still container object owns the aggregated object.
So if we delete class A that doesn't mean that class B will also be deleted. E.g. none, or many, teachers can belong to one or many departments.
The relationship between Teachers and Departments is aggregation.
3. Composition
Class A owns Class B.
E.g. Body consists of Arm, Head, Legs. BankAccount consists of Balance and TransactionHistory.
So if class A gets deleted then also class B will get deleted.
Direct association has nothing in common with the other three. It does not belong to UML at all, it is the IBM requirements modelling term.
As for others,
Association A->B is a child of Dependency. Association means, that A (or its instance) has some easy way to get to instance of B. For example, a.x.y.b. Or by function, or by some local variable. Or by a direct reference or pointer, or something else (there are many languages in the world). As you see, there is no strict border between dependency and association.
One of attributes of Association is Aggregation, it can have values: None, shared (often incorrectly called aggregation), and composition.
If A (or instance) has some (or one) instances of B so, that destroying of association means the destroying of B instances, it is the composition.
If you or a tool author had decided, that some has-a relationship, that is weaker that composition, needs to be specially shown, you can use shared aggregation. Usually it is some collections of references to B in A.
There are some more interesting attributes of associations. Look here if you are interested.
An association between object types classifies relationships between objects of those types. For instance, the association Person-isEmployedBy-Enterprise may classify the relationships PeterMiller-isEmployedBy-IBM, SusanSmith-isEmployedBy-IBM and SarahAnderson-isEmployedBy-Google between the objects PeterMiller, SusanSmith and SarahAnderson of type Person as well as Google and IBM of type Enterprise. In other words, associations are relationship types with two or more object types participating in them. An association between two object types is called binary. While binary associations are more common, we may also have to deal with n-ary associations, where n is a natural number greater than 2. For instance, Person-isTreatedIn-Hospital-for-Disease is a 3-ary ("ternary") association between the object types Person, Hospital and Disease.
I guess that with "direct association" you mean a directional (or directed) association, which is an association (with a domain class and a range class) that represents a reference property in its domain class. Such a directional association has an "ownership dot" at its target end.
Please see this book chapter for more about associations.
And see my answer to this SO question for an explanation of aggregations and compositions.
If mapping inheritance using table per concrete class, while mapping concrete classes simply just as any other class (without union-subclass), NHibernate allows same PKs across subclasses. For example if you have BillingDetails and subclasses CreditCard and BankAccount, requesting all BillingDetails will get you all records from both tables, which can in turn have duplicate primary keys, which can be problematic due to not valid business identity of those objects. This of course is not the case with guids and such, but what about cases of plain identity or sequence id generators?
Simply, the question is, is there any real use of this scenarion of duplicate id keys when requesting polymorphic query like that? Could these duplicate ids make problems for NHibernate when handling entities internally?
Implicit polymorphism is necessary when mapping legacy models where the tables do not share a common key.
There are no problems with getting a list of BillingDetails with CreditCard and BankAccount instances sharing the same Id, because NH knows they are unrelated (and they are treated as related only for the purposes of querying, by running one query for each mapped subclass)
You should not use it for greenfield development.
I'm writing an application to help diabetics manage their condition. Information that is tracked includes blood sugar results, nutrition, exercise, and medication information.
In similar applications these entries are all presented in a single table view even though each type of entry has different fields. This data is manually tracked by many diabetics in a logbook, and I'm looking to keep that paradigm.
Each entry has some common information (timestamp, category, and notes) as well as information specific to each entry type. For instance, meal entries would have detailed nutrition information (carb counts, fiber, fat, etc), medication entries would indicate which medication and dosage, etc.
I've considered two different approaches but I'm getting stuck at both a conceptual level and a technical level when attempting to implement either. The first approach was to create an abstract entity to contain all the common fields and then create entities for each log entry type (meals, meds, bg, etc.) that are parented to the abstract entity. I had this all modeled out but couldn't quite figure out how to bind these items to an array controller to have them show up in a single table view.
The second approach is to have one entity that contains the common fields, and then model the specific entry types as separate entities that have a relationship back to the common record (sort of like a decorator pattern). This was somewhat easier to build the UI for (at least for the common field entity), but I come to the same problem when wanting to bind the specific data entities.
Of course the easiest approach is to just throw all the fields from each different entry type into one entity but that goes against all my sensibilities. And it seems I would still run into a similar problem when I go to bind things to the table view.
My end goal is to provide an interface to the user that shows each entry in chronological order in a unified interface instead of having to keep a separate list of each entry type. I'm fine with adding code where needed, but I'd like to use the bindings as much as possible.
Thanks in advance for any advice.
Don't get bogged down with entity inheritance. You shouldn't use it save duplicate attributes like you would with classes. It's major use is allow different entities to be in the same relationship. Also, entity inheritance and class inheritance don't have to overlap. You can have a class inheritance hierarchy without an entity inheritance hierarchy.
I'm not sure I understand exactly what you really need but here's some generic advice: You shouldn't create your data model based on the needs of the UI. The data model is really a simulation of the real-world objects, events or conditions that your app deals with. You should create your data model first and foremost to accurately simulate the data. Ideally, you should create a data model that could be used with any UI e.g. command-line, GUI, web page etc.
Once your model is accurately setup, then whipping up the UI is usually easy.
What is the best way to design repositories for complex objects, assuming use of an ORM such as NHibernate or Entity Framework?
I am creating an app using Entity Framework 4. The app uses complex objects--a Foo object contains a collection of Bar objects in a Foo.Bars property, and so on. In the past, I would have created a FooRepository, and then a BarRepository, and I would inject a reference to the BarRepository into the FooRepository constructor.
When a query is passed to the FooRepository, it would call on the BarRepository as needed to construct the Foo.Bars property for each Foo object. And when a Foo object is passed to the FooRepository for persistence, the repository would call the BarRepository to persist the objects in the Foo.Bars property.
My question is pretty simple: Is that a generally accepted way to set up the repositories? Is there a better approach? Thanks for your help.
In domain-driven design, there is the concept of a "root aggregate" object. The accepted answer to a related question has good information on what it is and how you would use it in your design. I don't know about the Entity Framework but NHibernate does not require the usage pattern you are describing. As long as all the nested objects and their relationships are properly mapped to tables, saving the aggregate root will also save all its child object. The exception is when a nested object has specific business logic that needs to performed as part of its access or persistence. In that case, you would need to pass the "child" repositories so you are not duplicating that business logic.
Repository pattern helps grouping of business transactions among related entities. Meaning if you have two domain objects foo and bar and have a common transactions like GetList(),Update() then a common repository like FoobarReporsitory can be created. You can even abstract that to an interface called IFoobarReporsitory to make application loosely coupled.
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).