Question

I´m implementing Identity map pattern and DataMapper pattern in my project. But I have some problems.

When I´m getting data from database by Gateway I´m creating new instance of object and return List ...

What is the best way to implement getting data from database with regard to Identy Map ? I want to get patients from database and show these data to user..

What about ID of objects in Identity map ? My solution (in my mind) : 1) Create new object with some default id 2) Save object to databse 3) Get id of last object in database 4) Set new id of object 5) Save to cache with new id ....

It is good solution ?

Thanks for your help!

My identy map object(singleton):

public class PacientMap
{

    //Cache obsahující jednotlivé instance entiti

    private static PacientMap _instance;
    private Dictionary<int, Pacient> _cache; // Slouží k ukládání objektů pacient

    //Privátní konstruktor, (zaručí mi, že nedojde k vytvoření další instance) => metoda PacientGetInstance ho zavolá jen jednou
    private PacientMap()
    {
            _cache = new Dictionary<int, Pacient>();
    }

    //Metoda pro vytvoreni objektu jedinacek
    public static PacientMap PacientGetInstance()
    {   
        //Je-li promenna instance null, tak se vytvori objekt
        if (_instance == null)
        {
            _instance = new PacientMap();
        }

       //Vratime jedinacka
        return _instance;
    }



    /***********************************
     Vrátí jedinečnou instanci pro zadaný klíč. Pokud instance neexistuje, bude
     vytvořena a uložena do cache.
    ***************************************/
    public Pacient GetPacient(int klic)
    {
        // Pokud je v cache objekt s daným klicem
        if (_cache.ContainsKey(klic))
        {
            //Vrátím objekt
            return _cache[klic];
        }
        // Pokud jsem ho v cache nenasel
        // Zkusím ho najít v databázi
        if (SerachInDb(klic))
        {
            // Pokud byl nalezen v DB, byl automaticky uložen do cahe a jen si ho pod jeho id v cahe nejdu
            return _cache[klic];
        }

        // Pokud nebyl nikde nalezen, vyhodíme chybu
        throw new Exception();
    }

    /// <summary>
    /// Najde Pacienta v databází a pokud ho najde ulozí ho do cache a vrací TRUE
    /// Pokud ho nenejde vrací FALSE
    /// </summary>
    /// <param name="klic"></param>
    /// <returns></returns>
    private bool SerachInDb(int klic)
    {

        Pacient pac = PacientDataGateway.GetInstance().SelectByPacientId(klic);

        if (pac == null)
        {
            return false;
        }

        _cache.Add(klic, pac);

        return true;
    }

    /// <summary>
    /// Vytvoření nového pacienta
    /// </summary>
    /// <param name="klic"></param>
    /// <param name="pacient"></param>
    /// <returns></returns>
    public bool Add(int IdPacienta, string jmeno, string prijmeni, DateTime datumNarozeni, string cisloPojisteni, string telefon, int zubarId)
    {
        if(SerachInDb(zubarId))
        {
            return true;
        }

        Pacient pacient = new Pacient(0, jmeno, prijmeni, datumNarozeni, cisloPojisteni, telefon, zubarId);

        if(PacientDataGateway.GetInstance().insert(pacient))
        {
            // TODO: Selectnu si púoslední záznam z DB a zjistím so jeho id
        }

        return true;
    }

}

And there is Pacient Mapper:

      public List<Pacient> SelectPacient()
    {
        Database db = new Database();
        db.Connect();

        SqlCommand command = db.CreateCommand("SELECT ID,jmeno,prijmeni,datumNarozeni,cisloPojisteni,telefon,Zubarid FROM pacient");

        SqlDataReader reader = db.Select(command);

        List<Pacient> pacienti = new List<Pacient>();

        Pacient pacient = null;
        while (reader.Read())
        {
            pacient = new Pacient();

            pacient.Id = reader.GetInt32(0);
            pacient.Jmeno = reader.GetString(1);
            pacient.Prijmeni = reader.GetString(2);
            pacient.DatumNarozeni = reader.GetDateTime(3);
            pacient.CisloPojisteni = reader.GetString(4);
            pacient.Telefon = reader.GetString(5);
            pacient.idZubare = reader.GetInt32(6);

            pacienti.Add(pacient);
        }
        reader.Close();
        db.Close();

        return pacienti;
    }
Was it helpful?

Solution

You must check your IdentityMap for the presence of an object before getting it from the database, this prevents you getting multiple copies of the same object and subsequent update conflicts. When you ask for a single object by Id, you can check the IdentityMap for the object first and then only call the database if you don't already have the object. For more than one object, this cannot be done as the results are non-deterministic. You have to query the database and then check the map, filling in the gaps.

Ultimately, the IdentityMap's job is to ensure that only one in-memory copy of an object exists for a give scope at any time. If yours is achieving this, then it's job done.

If your map is keyed by Id, you will need an Id before you add it to the map. This can be done on the client or via in insert query. I prefer client-side allocation of keys as you don't have to make a round-trip to get an Id. However, your proposed approach seems ok.

My own implementation of an IdentityMap is keyed by Type and then Id using nested Dictionaries. This is handy if your keys are table-scoped.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top