b.Identity Map

  1. Motivation
    1. Ensures that each object gets loaded only once by keeping every loaded object in a map. Looks up objects using the map when referring to them.
  2. Summary
    1. An Identity Map keeps a record of all objects that have been read from the database in a single business transaction. 
    2. Whenever you want an object, you check the Identity Map first to see if you already have it.
  3. When to Use
    1. In general you use an Identity Map to manage any object brought from a database and modified and two in-memory objects correspond to a single database record.
    2. When you need to a cache for database reads, which means that you can avoid going to the database each time you need some data. 
    3. When you need to handle update conflicts within a single session.
  4. Implementation
    1. Usually primary key or surrogate key are use to create identity map and usually one map is created per data table.
  5. Related Patterns
    1. Unity of Work : It usually consumes the Identity map pattern for object tracking
  6. Related Technologies 
    1. Dot.net Hash Table or dictionary can be used for implementing identity map
  7. Specific Considerations 
    1. Map Keys 
      1. The first thing to consider is the key for the map. The obvious choice is the primary key of the corresponding database table.
      2. This works well if the key is a single column and immutable. 
      3. A surrogate primary key fits in very well with this approach because you can use it as the key in the map. 
      4. The key will usually be a simple data type so the comparison behavior will work nicely.
    2. Map Storage
      1. Identity Maps need to be somewhere where they're easy to find. They're also tied to the process context you're working in.
      2. You need to ensure that each session gets it's own instance that's isolated from any other session's instance. Thus, you need to put the Identity Map on a session-specific object.
      3. If you're using Unit of Work that's by far the best place for the Identity Maps since the Unit of Work is the main place for keeping track of data coming in or out of the database.
      4. If you don't have a Unit of Work the best bet is a Registry that's tied to the session.
  8. References
    1. Overview Tutorials
      1. http://martinfowler.com/eaaCatalog/identityMap.html
      2. http://msdn.microsoft.com/en-us/magazine/dd569757.aspx#id0400073
    2. Further References
      1. None