ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 合并多个业务库 2 在系统中使用ConditionalSQLManager,可以把多个SQLManager合并成一个,比如上个例子的订单和商品俩个SQLManager,可以做合并。ConditionalSQLManager 代理了SQLManager的操作,并根据传入的Entity 如下例子来自源码[S6MoreDatabase.conditional](https://gitee.com/xiandafu/beetlsql/blob/master/sql-samples/sql-sample-quickstart/src/main/java/org/beetl/sql/test/S6MoreDatabase.java) ```java SQLManager a = SampleHelper.init(); SQLManager b = SampleHelper.init(); Map<String, SQLManager> map = new HashMap<>(); map.put("a", a); map.put("b", b); SQLManager sqlManager = new ConditionalSQLManager(a, map); //不同用户,用不同sqlManager操作,存入不同的数据库 UserData user = new UserData(); user.setName("hello"); user.setDepartmentId(2); sqlManager.insert(user); DepartmentData dept = new DepartmentData(); dept.setName("dept"); sqlManager.insert(dept); ``` ConditionalSQLManager 默认是通过操作POJO上的@TargetSQLManager注解来区分 ```java @Data @Table(name = "sys_user") @TargetSQLManager("a") public static class UserData { @Auto private Integer id; private String name; private Integer departmentId; } @Data @Table(name = "department") @TargetSQLManager("b") public static class DepartmentData { @Auto private Integer id; private String name; } ``` Conditional接口决定了使用何种数据库,以ConditionalSQLManager.DefaultConditional为例子,会返回真正的SQLManager ```java public static class DefaultConditional implements Conditional{ @Override public SQLManager decide(Class pojo,SQLManager defaultSQLManager, Map<String, SQLManager> sqlManagerMap) { TargetSQLManager an = (TargetSQLManager)pojo.getAnnotation(TargetSQLManager.class); if(an==null){ return defaultSQLManager; } String sqlManagerName = an.value(); SQLManager target = sqlManagerMap.get(sqlManagerName); if(target==null){ throw new IllegalArgumentException("未发现目标sqlManager "+sqlManagerName+" from "+sqlManagerMap.keySet()); } return target; } } ``` 你也可以定义一个自己的Conditional,来决定使用那个SQLManager进行操作,甚至参考ConditionalSQLManager实现自己的对SQLManager的代理封装