Spring Data Access Object (DAO)

by GarciaPL on Saturday 26 October 2013

I would like to present a small example of using Data Access Object (DAO) in Spring. This is a kind of component which provides unified interface to communication between application and source of data for instance database or file. Application using DAO does not have to know the way the data is stored or manipulated in database. This component is commonly used in MVC (Model-View-Controller) which allows to separate data access model from business logic and presentation layer. In this example datasource is NoSQL Database MongoDB.

Below I put some example of DAO Entity called SettingsDao and its Implementation called SettingsDaoImpl.

Entity SettingsDAO :

package pl.eventoo.mongodb.dao;

import pl.eventoo.domain.Settings;

/**
 * Interface of credentials settings
 *
 * @author lukasz
 */
public interface SettingsDao {

    /**
     * Interface for save credentials
     *
     * @param settings 
     */
    public void saveSettings(Settings settings);
    
    /**
     * Interface for update credentials
     * 
     * @param settings
     * @return
     */
    public boolean updateSettings(Settings settings);

    /**
     * Interface for read credentials
     *
     * @return
     */
    public Settings readSettings();
}



Implementation of Entity DAO SettingsDaoImpl :

package pl.eventoo.mongodb.dao;

import com.google.code.morphia.DAO;
import com.google.code.morphia.query.UpdateOperations;
import com.google.code.morphia.query.UpdateResults;
import pl.eventoo.domain.Settings;
import pl.eventoo.mongodb.factory.MongoConnectionManager;

/**
 * Implementation Dao for credentials settings
 *
 * @author lukasz
 */
public class SettingsDaoImpl extends DAO Settings, String implements SettingsDao {

    public SettingsDaoImpl() {
        super(Settings.class, MongoConnectionManager.instance().getDb());
    }

    @Override
    public void saveSettings(Settings settings) {
        save(settings);
    }

    @Override
    public Settings readSettings() {
        return ds.find(Settings.class).get();
    }

    @Override
    public boolean updateSettings(Settings settings) {
        UpdateOperations createUpdateOperations = ds.createUpdateOperations(Settings.class).set("interval_cron", settings.getInterval_cron()).set("time_difference_event", settings.getTime_difference_event());
        UpdateResults update = ds.update(ds.createQuery(Settings.class), createUpdateOperations);
        return update.getHadError();
    }
}


Reference : [1] Springbyexample.org Person DAO [2] Spring Framework 3.0 Docs DAO [3] Spring Framework 3.2 Docs MVC
[4] Pastebin Settings DAO Source
[5] Pastebin Settings Implementation DAO Source