Repository 与 DAO

资源库(Repository)             ------   查阅一些资料,小见解

    协调领域和数据层映射层,利用类似于集合的接口来访问领域对象。

    它将分离了数据库访问层跟领域对象的代码细节。

    Repository在新解释中,其有两中分类:面向集合的资源库 跟 面向数据库的资源库。

    面向集合方式的资源库:

        访问方式近似于集合操作。通常从集合中获取得到领域对象,改领域对象在操作改变数据之后,再次从资源库或取改对象,其值跟原来的领域修改过的领域对象值一至。

简单的面向集合方式的Repository一般有

add() , remove(), get() 这些方法。 不同于,面向数据库型的Repository,在获取某一领域对象修改后要额外调用save()方法,来同步原来Repository数据。

public class TestProductRepository
{
    public void testIdof()
    {
        Product found = Registry.productRepository()
                            .prodcutOf(new ProductId(1L));
        
        
        found.name("New Name");

        Product otherFound = Registry.productRepository()
                                .productOf(new Prodcut(1L));
        
        assertEquals( found.name(), otherFound.name()  );
    }
}



上面测试例子说明在修改在Reposiotry取出来的领域对象引用操作改变后,跟你再一次从Repository中取出一致的。

    在hibernate中,session关闭时检查相关对象dirty状态,进行与数据库同步,使得我们可以实现面向集合方式的Repository。

     面向数据库方式的Repository

与面向集合方式的Repository类似,主要区别在于,我们需要save()方式,让新修改数据同步到Repository中去。

public class TestProductRepository
{
    public void testIdof()
    {
        Product found = Registry.productRepository()
                            .prodcutOf(new ProductId(1L));
        
        
        found.name("New Name");

        Product otherFound = Registry.productRepository()
                                .productOf(new Prodcut(1L));
        
        assertNotEquals( found.name(), otherFound.name()  );

        
        Registry.productRepository().save(found);
        

         otherFound = Registry.productRepository()
                          .productOf(new Prodcut(1L));
        

        assertEquals( found.name(), otherFound.name()  );
    }
}

Repository 与 DAO

    有时Reposiotry与DAO被当作同意词看待。有一个明显的区分。

    DAO通常是对数据库表的封装,当我们使用事务脚本时,经常创建贫血的只有简单get/set的对象,大多根据一行数据的映射。DAO对这一层的数据库访问进行、封装,可以看待为对数据的CRUD,交由事务脚本处理。

    Reposiotry使用数据映射器或其他技术,进行存储与获取操作是的领域对象,可能是一系列的聚合或实体,更加的面向对象,同时也有着对数据访问层的封装。

    通常我们可以将Reposiotry跟DAO一样看待,但我们知道Repository是面向领域模型的,而DAO则面向的是数据的。

    


转载于:https://my.oschina.net/XzhiF/blog/265165

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值