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:
-
mybatis.config-location=classpath:mybatis/mybatis-config.xml
-
-
spring.datasource.test1.jdbc-url=jdbc:mysql://localhost:3306/test1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
-
spring.datasource.test1.username=root
-
spring.datasource.test1.password=root
-
spring.datasource.test1.driver-class-name=com.mysql.cj.jdbc.Driver
-
-
spring.datasource.test2.jdbc-url=jdbc:mysql://localhost:3306/test2?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
-
spring.datasource.test2.username=root
-
spring.datasource.test2.password=root
-
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
-
@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);
-
}
-
}
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
-
@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 @Bean
need 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.test1
com.neo.mapper.test2
-
public interface User1Mapper {
-
List<UserEntity> getAll();
-
UserEntity getOne(Long id);
-
void insert(UserEntity user);
-
void update(UserEntity user);
-
void delete(Long id);
-
}
xml layer
-
<mapper namespace="com.neo.mapper.test1.User1Mapper" >
-
<resultMap id="BaseResultMap" type="com.neo.model.User" >
-
<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.model.User" >
-
INSERT INTO
-
users
-
(userName,passWord,user_sex)
-
VALUES
-
(#{userName}, #{passWord}, #{userSex})
-
</insert>
-
-
<update id="update" parameterType="com.neo.model.User" >
-
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
Testing may be used SpringBootTest, may be placed in the Controller, where only the paste layer using the Controller
-
@RestController
-
public 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);
-
}
-
-
}
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.