根据上面Primary数据源的定义,在com.didispace.chapter39.p包下,定义Primary数据源要用的实体和数据访问对象,比如下面这样:
@Data @NoArgsConstructor public class UserPrimary { private Long id; private String name; private Integer age; public UserPrimary(String name, Integer age) { this.name = name; this.age = age; } } public interface UserMapperPrimary { @Select("SELECT * FROM USER WHERE NAME = #{name}") UserPrimary findByName(@Param("name") String name); @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})") int insert(@Param("name") String name, @Param("age") Integer age); @Delete("DELETE FROM USER") int deleteAll(); }根据上面Secondary数据源的定义,在com.didispace.chapter39.s包下,定义Secondary数据源要用的实体和数据访问对象,比如下面这样:
@Data @NoArgsConstructor public class UserSecondary { private Long id; private String name; private Integer age; public UserSecondary(String name, Integer age) { this.name = name; this.age = age; } } public interface UserMapperSecondary { @Select("SELECT * FROM USER WHERE NAME = #{name}") UserSecondary findByName(@Param("name") String name); @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})") int insert(@Param("name") String name, @Param("age") Integer age); @Delete("DELETE FROM USER") int deleteAll(); } 测试验证完成了上面之后,我们就可以写个测试类来尝试一下上面的多数据源配置是否正确了,先来设计一下验证思路:
往Primary数据源插入一条数据
从Primary数据源查询刚才插入的数据,配置正确就可以查询到
从Secondary数据源查询刚才插入的数据,配置正确应该是查询不到的
往Secondary数据源插入一条数据
从Primary数据源查询刚才插入的数据,配置正确应该是查询不到的
从Secondary数据源查询刚才插入的数据,配置正确就可以查询到
具体实现如下:
@Slf4j @RunWith(SpringRunner.class) @SpringBootTest @Transactional public class Chapter39ApplicationTests { @Autowired private UserMapperPrimary userMapperPrimary; @Autowired private UserMapperSecondary userMapperSecondary; @Before public void setUp() { // 清空测试表,保证每次结果一样 userMapperPrimary.deleteAll(); userMapperSecondary.deleteAll(); } @Test public void test() throws Exception { // 往Primary数据源插入一条数据 userMapperPrimary.insert("AAA", 20); // 从Primary数据源查询刚才插入的数据,配置正确就可以查询到 UserPrimary userPrimary = userMapperPrimary.findByName("AAA"); Assert.assertEquals(20, userPrimary.getAge().intValue()); // 从Secondary数据源查询刚才插入的数据,配置正确应该是查询不到的 UserSecondary userSecondary = userMapperSecondary.findByName("AAA"); Assert.assertNull(userSecondary); // 往Secondary数据源插入一条数据 userMapperSecondary.insert("BBB", 20); // 从Primary数据源查询刚才插入的数据,配置正确应该是查询不到的 userPrimary = userMapperPrimary.findByName("BBB"); Assert.assertNull(userPrimary); // 从Secondary数据源查询刚才插入的数据,配置正确就可以查询到 userSecondary = userMapperSecondary.findByName("BBB"); Assert.assertEquals(20, userSecondary.getAge().intValue()); } } 代码示例本文的相关例子可以查看下面仓库中的chapter3-9目录:
Github:https://github.com/dyc87112/SpringBoot-Learning/
Gitee:https://gitee.com/didispace/SpringBoot-Learning/