Spring Boot (seven): Mybatis Multiple Data Sources Minimalist solutions

Speaking of multiple data sources, usually to solve problems that do, the main connection from different sub-library complex needs or business model to support the business. We encountered the latter, find a lot, mostly to do Jpa solutions based on multiple data sources, either the old Spring multi data source solution, there is the use of dynamic switching Aop, feeling a little complicated, in fact, I was just looking for a simple multi-data support it, toss sorted out for two hours, for your reference.

Ado directly on the bar code

We Mybatis Xml version, for example, to show you how to how to configure multiple data sources.

Profiles

Pom not posted relatively simple package that relies on the dependence, the configuration of the main database here:

  1. mybatis.config-location=classpath:mybatis/mybatis-config.xml

  2.  

  3. spring.datasource.test1.jdbc-url=jdbc:mysql://localhost:3306/test1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true

  4. spring.datasource.test1.username=root

  5. spring.datasource.test1.password=root

  6. spring.datasource.test1.driver-class-name=com.mysql.cj.jdbc.Driver

  7.  

  8. spring.datasource.test2.jdbc-url=jdbc:mysql://localhost:3306/test2?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true

  9. spring.datasource.test2.username=root

  10. spring.datasource.test2.password=root

  11. spring.datasource.test2.driver-class-name=com.mysql.cj.jdbc.Driver

Test1 test2 a library and a library, which test1 bit main library, you must specify the main library in the use of the process, or will be error.

Data source configuration

  1. @Configuration

  2. @MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef = "test1SqlSessionTemplate")

  3. public class DataSource1Config {

  4.  

  5. @Bean(name = "test1DataSource")

  6. @ConfigurationProperties(prefix = "spring.datasource.test1")

  7. @Primary

  8. public DataSource testDataSource() {

  9. return DataSourceBuilder.create().build();

  10. }

  11.  

  12. @Bean(name = "test1SqlSessionFactory")

  13. @Primary

  14. public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception {

  15. SqlSessionFactoryBean bean = new SqlSessionFactoryBean();

  16. bean.setDataSource(dataSource);

  17. bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));

  18. return bean.getObject();

  19. }

  20.  

  21. @Bean(name = "test1TransactionManager")

  22. @Primary

  23. public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {

  24. return new DataSourceTransactionManager(dataSource);

  25. }

  26.  

  27. @Bean(name = "test1SqlSessionTemplate")

  28. @Primary

  29. public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {

  30. return new SqlSessionTemplate(sqlSessionFactory);

  31. }

  32. }

The most critical piece of the place is, the injection layer by layer, first create a DataSource, and then re-create SqlSessionFactory create a transaction, to the final packaging SqlSessionTemplate in. Wherein the mapper need to specify the sub-library file address, and the sub-layer codes library dao

  1. @MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef = "test1SqlSessionTemplate")

This indicates that the scanning dao annotation layer, and injected to the specified SqlSessionTemplate dao layer. All  @Beanneed to specify the correct name according to.

xml dao layer and layer

dao layer and xml points need to follow the library to a different directory, such as: test1 library dao layer   under the package, test2 library com.neo.mapper.test1com.neo.mapper.test2

  1. public interface User1Mapper {

  2. List<UserEntity> getAll();

  3. UserEntity getOne(Long id);

  4. void insert(UserEntity user);

  5. void update(UserEntity user);

  6. void delete(Long id);

  7. }

xml layer

  1. <mapper namespace="com.neo.mapper.test1.User1Mapper" >

  2. <resultMap id="BaseResultMap" type="com.neo.model.User" >

  3. <id column="id" property="id" jdbcType="BIGINT" />

  4. <result column="userName" property="userName" jdbcType="VARCHAR" />

  5. <result column="passWord" property="passWord" jdbcType="VARCHAR" />

  6. <result column="user_sex" property="userSex" javaType="com.neo.enums.UserSexEnum"/>

  7. <result column="nick_name" property="nickName" jdbcType="VARCHAR" />

  8. </resultMap>

  9.  

  10. <sql id="Base_Column_List" >

  11. id, userName, passWord, user_sex, nick_name

  12. </sql>

  13.  

  14. <select id="getAll" resultMap="BaseResultMap" >

  15. SELECT

  16. <include refid="Base_Column_List" />

  17. FROM users

  18. </select>

  19.  

  20. <select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >

  21. SELECT

  22. <include refid="Base_Column_List" />

  23. FROM users

  24. WHERE id = #{id}

  25. </select>

  26.  

  27. <insert id="insert" parameterType="com.neo.model.User" >

  28. INSERT INTO

  29. users

  30. (userName,passWord,user_sex)

  31. VALUES

  32. (#{userName}, #{passWord}, #{userSex})

  33. </insert>

  34.  

  35. <update id="update" parameterType="com.neo.model.User" >

  36. UPDATE

  37. users

  38. SET

  39. <if test="userName != null">userName = #{userName},</if>

  40. <if test="passWord != null">passWord = #{passWord},</if>

  41. nick_name = #{nickName}

  42. WHERE

  43. id = #{id}

  44. </update>

  45.  

  46. <delete id="delete" parameterType="java.lang.Long" >

  47. DELETE FROM

  48. users

  49. WHERE

  50. id =#{id}

  51. </delete>

  52.  

  53. </mapper>

test

Testing may be used SpringBootTest, may be placed in the Controller, where only the paste layer using the Controller

  1. @RestController

  2. public class UserController {

  3.  

  4. @Autowired

  5. private User1Mapper user1Mapper;

  6.  

  7. @Autowired

  8. private User2Mapper user2Mapper;

  9.  

  10. @RequestMapping("/getUsers")

  11. public List<UserEntity> getUsers() {

  12. List<UserEntity> users=user1Mapper.getAll();

  13. return users;

  14. }

  15.  

  16. @RequestMapping("/getUser")

  17. public UserEntity getUser(Long id) {

  18. UserEntity user=user2Mapper.getOne(id);

  19. return user;

  20. }

  21.  

  22. @RequestMapping("/add")

  23. public void save(UserEntity user) {

  24. user2Mapper.insert(user);

  25. }

  26.  

  27. @RequestMapping(value="update")

  28. public void update(UserEntity user) {

  29. user2Mapper.update(user);

  30. }

  31.  

  32. @RequestMapping(value="/delete/{id}")

  33. public void delete(@PathVariable("id") Long id) {

  34. user1Mapper.delete(id);

  35. }

  36.  

  37. }

Mybatis an annotated version of a data source to configure multiple versions consistent and Xml, exemplary structures project directly reference the end of the text.

Article content has been upgraded to Spring Boot 2.x

Sample Code -https: //github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-mybatis

 

Wonderful review:

Relationship in Java hashCode () and equals (): The point of the interview

Connected to the container [Docker series -7]

Now the technology wave, we in the end what to do?

 

highly recommended:

"Java technology geek" knowledge planet Limited Time Offer join now only  50  yuan, only before 1000, Jibukeshi or never. As early as possible action!

https://t.zsxq.com/J6Em2nU

 

Introducing:

Java technology geeks public number, is founded by a group of people who love Java technology development, focused on sharing of original, high-quality Java articles. If you feel that our article is not bad, please help appreciated, watching, forwarding support, encourage us to share a better article.

 

Guess you like

Origin www.cnblogs.com/justdojava/p/11098173.html