遇到的问题
1,@Primary注解是必要的,不然会出现异常.
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] is defined: expected single matching bean but found 2: test1DataSource,test2DataSource
2,因为存在多个DataSource,SqlSessionFactory,PlatformTransactionManager,SqlSessionTemplate所以要使用"name"来区分.
3,SqlSessionTemplate如果不配置,在访问主数据源的数据没有问题,但是访问另一个数据源就会出现异常.
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): cn.zz.mapper1.UserMapper1.findAll
4,MyBatis@Configuration上需要加注解
@MapperScan(basePackages = "cn.zz.mapper1", sqlSessionTemplateRef = "test2SqlSessionTemplate")
结构
数据源
package cn.zz.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "cn.zz.mapper", sqlSessionTemplateRef = "test1SqlSessionTemplate")
public class DataSource1 {
@Bean(name = "test1DataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary")
@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/*.xml"));
return bean.getObject();
}
@Bean(name = "test1TransactionManager")
@Primary
public PlatformTransactionManager 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);
}
}
package cn.zz.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "cn.zz.mapper1", sqlSessionTemplateRef = "test2SqlSessionTemplate")
public class DataSource2 {
@Bean(name = "test2DataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "test2SqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis1/*.xml"));
return bean.getObject();
}
@Bean(name = "test2TransactionManager")
public PlatformTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "test2SqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
Controller
package cn.zz.controller;
import cn.zz.model.User;
import cn.zz.service.UserService;
import cn.zz.service1.UserService1;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class UserController {
private Logger logger = Logger.getLogger(UserController.class);
@Autowired
private UserService userService;
@Autowired
private UserService1 userService1;
@RequestMapping("/save")
@ResponseBody
public User save() {
User user = userService.save("zz",27,"72");
return user;
}
@RequestMapping("/save1")
@ResponseBody
public String save1() {
userService.save1("zz",27,"72");
return "ok";
}
@RequestMapping("/getUserInfo")
@ResponseBody
public User getUserInfo() {
User user = userService.getUserInfo();
if(user!=null){
System.out.println("user.getName():"+user.getName());
logger.info("user.getAge():"+user.getAge());
}
return user;
}
@RequestMapping("/findAll")
@ResponseBody
public List<User> findAll() {
List<User> user = userService.findAll();
return user;
}
@RequestMapping("/findAll1")
@ResponseBody
public List<User> findAll1() {
List<User> user = userService1.findAll1();
return user;
}
}
Service
package cn.zz.service;
import cn.zz.mapper.UserMapper;
import cn.zz.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
- @Service
@Transactional
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserInfo(){
User user=userMapper.findUserInfo();
//User user=null;
return user;
}
public User save(String name, Integer age, String password) {
User user=new User();
user.setName(name);
user.setAge(age);
user.setPassword(password);
userMapper.save(user);
return user;
}
public List<User> findAll() {
List<User> user=userMapper.findAll();
//User user=null;
return user;
}
public void save1(String zz, int i, String s) {
User user=new User();
user.setName(zz);
user.setAge(i);
user.setPassword(s);
userMapper.save1(user);
}
}
package cn.zz.service1;
import cn.zz.mapper1.UserMapper1;
import cn.zz.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class UserService1 {
@Autowired
private UserMapper1 userMapper1;
public List<User> findAll1() {
List<User> user = userMapper1.findAll();
//User user=null;
return user;
}
}
Mapper
package cn.zz.mapper;
import cn.zz.model.User;
import java.util.List;
/**
* Created by zl on 2015/8/27.
*/
//@Repository(value = "sqlSessionFactoryBean1")
public interface UserMapper {
public User findUserInfo();
void save(User user);
List<User> findAll();
void save1(User user);
}
package cn.zz.mapper1;
import cn.zz.model.User;
import java.util.List;
public interface UserMapper1 {
public User findUserInfo();
void save(User user);
List<User> findAll();
void save1(User user);
}
Mapper.xml
<?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="cn.zz.mapper.UserMapper">
<select id="findUserInfo" resultType="cn.zz.model.User">
select id,name,age,password from user;
</select>
<select id="findAll" resultType="cn.zz.model.User">
select id,name,age,password from user;
</select>
<insert id="save"
keyProperty="id" keyColumn="id" useGeneratedKeys="true">
INSERT INTO user(name,age,password) VALUES(#{name}, #{age}, #{password});
</insert>
<insert id="save1">
INSERT INTO user(name,age,password) VALUES(#{name}, #{age}, #{password});
</insert>
</mapper>
<?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="cn.zz.mapper1.UserMapper1">
<select id="findUserInfo" resultType="cn.zz.model.User">
select id,name,age,password from user;
</select>
<select id="findAll" resultType="cn.zz.model.User">
select id,name,age,password from user;
</select>
<insert id="save"
keyProperty="id" keyColumn="id" useGeneratedKeys="true">
INSERT INTO user(name,age,password) VALUES(#{name}, #{age}, #{password});
</insert>
<insert id="save1">
INSERT INTO user(name,age,password) VALUES(#{name}, #{age}, #{password});
</insert>
</mapper>
实体类
package cn.zz.model;
public class User {
private Integer id;
private String name;
private Integer age;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
application.properties
spring.datasource.primary.url=jdbc:mysql://127.0.0.1:3306/zz?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull
spring.datasource.primary.username=root
spring.datasource.primary.password=123456
spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.secondary.url=jdbc:mysql://127.0.0.1:3306/zz1?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull
spring.datasource.secondary.username=root
spring.datasource.secondary.password=123456
spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver
Application
package cn.zz;
import org.apache.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//@EnableAutoConfiguration
@SpringBootApplication
//@ComponentScan
//@MapperScan("cn.no7player.mapper")
public class Application {
private static Logger logger = Logger.getLogger(Application.class);
/**
* Start
*/
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
logger.info("SpringBoot Start Success");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.unioncast</groupId>
<artifactId>unioncast-db-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>unioncast-db-service</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<repositories>
<repository>
<id>nexus</id>
<name>nexus</name>
<url>http://192.168.101.23:8081/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- 自己的公共库依赖 -->
<dependency>
<groupId>com.unioncast</groupId>
<artifactId>unioncast-common</artifactId>
<version>0.0.1-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator-docs</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-hal-browser</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId>
</dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<!--<scope>provided</scope>-->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- redis相关 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
<!-- c3p0连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>com.sun.jna</groupId>
<artifactId>jna</artifactId>
<version>3.0.9</version>
</dependency>
<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<!-- END Swagger -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<compilerArgument>-Xlint:unchecked</compilerArgument>
</configuration>
</plugin>
</plugins>
</build>
</project>