ctrip 开源 DAL 框架相关问题总结

ctrip 开源 DAL 框架 :https://github.com/ctripcorp/dal

1、分库情况下的新增、查询

如果配置分库、分表则新增、查询时必须满足以下条件之一,否则会抛出: DalException - Can not locate shard for testdb

  • 新增或查询的实体中包含用于分库或分表的字段
  • 使用 DalHints.setShardValue 来指定用于分库分表的值,使用这个值来计算 shardIndex

demo 代码:

    @Test
    public void testQueryByPk1() throws Exception {
        TestTable testTable = new TestTable();
        // 查询条件包含用于分库的字段:title
        testTable.setTitle("testA");
        testTable.setAuthor("frank");
        // 或使用以下 DalHints 指定用于分库的 shardValue
        //DalHints dalHints = new DalHints().setShardValue("testA");
        //Collection<TestTable> list = dao.queryBy(testTable,dalHints);
        Collection<TestTable> list = dao.queryBy(testTable);
        assertTrue(list != null && !list.isEmpty());
    }

 2、dal.xml 说明

<dal name="Dal.config">
    <databaseSets>
        <!--
            name - 逻辑数据库的名字
            provider - 逻辑数据库提供者是哪种类型的数据库,目前支持 mysql 和 sqlserver
            shardingStrategy - 指定分片的策略
         -->
        <databaseSet name="testdb" shardingStrategy="class=com.example.demo.dbshard.DbShardStrategy;columns=title;mod=2;" provider="mySqlProvider">
            <!--
             name - 物理数据库的代号
              databaseType - Master / Slave
              sharding - 数据库分片 id
              connectionString - 物理数据库的 id,用于在 datasource.xml 里面查找
            -->
            <add name="test_db_01" databaseType="Master" sharding="0" connectionString="test_db"/>
            <add name="test_db_02" databaseType="Master" sharding="1" connectionString="test_db_01"/>
        </databaseSet>
    </databaseSets>
</dal>

 

posted @ 2021-03-13 11:13  FrankYou  阅读(344)  评论(0编辑  收藏  举报