Springboot -- springboot + mybatis the simplest solution for multiple data sources,
Generally, many data sources are used to solve these problems. The master-slave mode or the business is complicated. You need to connect different database shards to support the business. Our project is the latter model. We have found a lot on the internet, mostly using jpa for multi-data source solutions, the old spring multi-data source solutions, and some using aop for dynamic switching, it seems a little complicated. In fact, I just wanted to find a simple multi-data support. I spent two hours sorting it out for your reference.
Let's talk a little bit about code.
Configuration File
The pom package does not post dependencies that are relatively simple. It mainly involves the configuration of the database:
mybatis.config-locations=classpath:mybatis/mybatis-config.xmlspring.datasource.test1.driverClassName = com.mysql.jdbc.Driverspring.datasource.test1.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8spring.datasource.test1.username = rootspring.datasource.test1.password = rootspring.datasource.test2.driverClassName = com.mysql.jdbc.Driverspring.datasource.test2.url = jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8spring.datasource.test2.username = rootspring.datasource.test2.password = root
One test1 database and one test2 database. The test1 master database must be specified during use. Otherwise, an error is reported.
Data source configuration
@Configuration@MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef = "test1SqlSessionTemplate")public class DataSource1Config { @Bean(name = "test1DataSource") @ConfigurationProperties(prefix = "spring.datasource.test1") @Primary public DataSource testDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "test1SqlSessionFactory") @Primary public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml")); return bean.getObject(); } @Bean(name = "test1TransactionManager") @Primary public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "test1SqlSessionTemplate") @Primary public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); }}
This is the most important part. First, a DataSource is created for one layer of injection. When SqlSessionFactory is created, the transaction is created, and finally packaged into SqlSessionTemplate. The mapper file address of the sub-database and the code from the sub-database to the layer must be specified.
@MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef = "test1SqlSessionTemplate")
This annotation indicates scanning the dao layer and injecting the specified SqlSessionTemplate to the dao layer. All @ beans must be named correctly.
Dao layer and xml Layer
The dao layer and xml must be divided into different directories according to the library. For example, the dao layer of the test1 library is under the com. neo. mapper. test1 package, and the test2 library is in the com. neo. mapper. test1 package.
public interface User1Mapper { List<UserEntity> getAll(); UserEntity getOne(Long id); void insert(UserEntity user); void update(UserEntity user); void delete(Long id);}
Xml Layer
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace="com.neo.mapper.test1.User1Mapper" > <resultMap id="BaseResultMap" type="com.neo.entity.UserEntity" > <id column="id" property="id" jdbcType="BIGINT" /> <result column="userName" property="userName" jdbcType="VARCHAR" /> <result column="passWord" property="passWord" jdbcType="VARCHAR" /> <result column="user_sex" property="userSex" javaType="com.neo.enums.UserSexEnum"/> <result column="nick_name" property="nickName" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List" > id, userName, passWord, user_sex, nick_name </sql> <select id="getAll" resultMap="BaseResultMap" > SELECT <include refid="Base_Column_List" /> FROM users </select> <select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" > SELECT <include refid="Base_Column_List" /> FROM users WHERE id = #{id} </select> <insert id="insert" parameterType="com.neo.entity.UserEntity" > INSERT INTO users (userName,passWord,user_sex) VALUES (#{userName}, #{passWord}, #{userSex}) </insert> <update id="update" parameterType="com.neo.entity.UserEntity" > UPDATE users SET <if test="userName != null">userName = #{userName},</if> <if test="passWord != null">passWord = #{passWord},</if> nick_name = #{nickName} WHERE id = #{id} </update> <delete id="delete" parameterType="java.lang.Long" > DELETE FROM users WHERE id =#{id} </delete> </mapper>
Test
SpringBootTest or Controller can be used for testing. Here, only the use of the Controller layer can be pasted.
@RestControllerpublic class UserController { @Autowired private User1Mapper user1Mapper; @Autowired private User2Mapper user2Mapper; @RequestMapping("/getUsers") public List<UserEntity> getUsers() { List<UserEntity> users=user1Mapper.getAll(); return users; } @RequestMapping("/getUser") public UserEntity getUser(Long id) { UserEntity user=user2Mapper.getOne(id); return user; } @RequestMapping("/add") public void save(UserEntity user) { user2Mapper.insert(user); } @RequestMapping(value="update") public void update(UserEntity user) { user2Mapper.update(user); } @RequestMapping(value="/delete/{id}") public void delete(@PathVariable("id") Long id) { user1Mapper.delete(id); }}
The last Source Code address here: https://github.com/ityouknow/spring-boot-starter
Source: http://mp.weixin.qq.com/s/ESI8K3voQKyl6Pj7zbK6qw
More learning resources: http://www.roncoo.com/course/list.html? CourseName = spring + boot