废话不多说,我们先把整个项目的结构整理一下:
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.0.0
org.springframework.boot
spring-boot-starter-jdbc
mysql
mysql-connector-java
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-tomcat
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-configuration-processor
com.alibaba
druid
1.0.26
org.springframework.boot
spring-boot-starter-aop
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-freemarker
这里我连接的是本地的两个库,可以修改localhost来连接其他ip数据库
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#spring.datasource.url=jdbc:mysql://localhost:3306/my
#spring.datasource.username=root
#spring.datasource.password=root
#the person datasource
datasource.person.driverClassName=com.mysql.jdbc.Driver
datasource.person.url=jdbc:mysql://localhost:3306/test
datasource.person.username=root
datasource.person.password=root
#the users datasource
datasource.users.driverClassName=com.mysql.jdbc.Driver
datasource.users.url=jdbc:mysql://localhost/lxy2018
datasource.users.username=root
datasource.users.password=root
# mybatis接口文件位置
mybatis.typeAliasesPackage=com.example.ninemysql.domain
# mybatis *.xml文件的位置
mybatis.mapperLocations=classpath*:/mapper/*Mapper.xml
#com/example/eightmysql/mapper/*.xml
spring.freemarker.cache = false
spring.thymeleaf.cache = false
default_encoding=UTF-8
locale=zh_CN
public class Student {
private int oldid;
private int id;
private String name;
private String university;
//类的构造函数,get(),set()方法
}
public class User {
private int oldid;
private int id;
private String username;
private String password;
//构造函数,get() set()方法
}
首先是common包的MyBatisConfig类,将配置文件中的信息链接数据源,再根据数据源创建SqlSessionFactory
@Configuration
@MapperScan(basePackages = "com.example.eightmysql.mapper")
public class MyBatisConfig {
@Autowired
private Environment env;
/**
* 创建数据源(数据源的名称:方法名可以取为XXXDataSource(),XXX为数据库名称,该名称也就是数据源的名称)
*/
@Bean
public DataSource myTestDbDataSource() throws Exception {
Properties props = new Properties();
props.put("driverClassName", env.getProperty("datasource.person.driverClassName"));
props.put("url", env.getProperty("datasource.person.url"));
props.put("username", env.getProperty("datasource.person.username"));
props.put("password", env.getProperty("datasource.person.password"));
return DruidDataSourceFactory.createDataSource(props);
}
@Bean
public DataSource myTestDb2DataSource() throws Exception {
Properties props = new Properties();
props.put("driverClassName", env.getProperty("datasource.users.driverClassName"));
props.put("url", env.getProperty("datasource.users.url"));
props.put("username", env.getProperty("datasource.users.username"));
props.put("password", env.getProperty("datasource.users.password"));
return DruidDataSourceFactory.createDataSource(props);
}
/**
* @Primary 该注解表示在同一个接口有多个实现类可以注入的时候,默认选择哪一个,而不是让@autowire注解报错
* @Qualifier 根据名称进行注入,通常是在具有相同的多个类型的实例的一个注入(例如有多个DataSource类型的实例)
*/
@Bean
@Primary
public DynamicDataSource dataSource(@Qualifier("myTestDbDataSource") DataSource myTestDbDataSource,
@Qualifier("myTestDb2DataSource") DataSource myTestDb2DataSource) {
DynamicDataSource dataSource = new DynamicDataSource();
Map
然后,建立datasource包,设置动态数据源切换
//保存一个线程安全的DatabaseType容器
public class DatabaseContextHolder {
private static final ThreadLocal contextHolder = new ThreadLocal<>();
public static final Logger log = LoggerFactory.getLogger(DatabaseContextHolder.class);
public static void setDatabaseType(DatabaseType type) {
log.info("切换到{}数据源", type);
contextHolder.set(type);
}
public static DatabaseType getDatabaseType() {
return (contextHolder.get());
}
public static void clearDatabaseType(){
contextHolder.remove();
}
}
public class DynamicDataSource extends AbstractRoutingDataSource {
private static final Logger log = LoggerFactory.getLogger(DynamicDataSource.class);
@Override
protected Object determineCurrentLookupKey() {
log.debug("数据源为===>{}", DatabaseContextHolder.getDatabaseType());
return DatabaseContextHolder.getDatabaseType();
}
}
@Aspect
@Component
public class DataSourceAspect {
@Pointcut("execution(* com.example.ninemysql.dao.*.*(..))")
public void JoinPoint(){
}
//使用定义切点表达式的方法进行点表达式的引入
@Before("JoinPoint()")
public void setDataSourceKey(JoinPoint point){
//如果连接点所属的类实例是StudentDao
if(point.getTarget() instanceof StudentDao){
DatabaseContextHolder.setDatabaseType(DatabaseType.lxy2018);
}else{//连接点是UserDao,可以不写是默认的数据源
DatabaseContextHolder.setDatabaseType(DatabaseType.test);
}
}
}
@Controller
public class DeleteController {
ModelAndView modelAndView;
@Autowired
private UserService userService;
@Autowired
private StudentService studentService;
//修改页面
@RequestMapping("/toupdpage")
public ModelAndView updpage(@RequestParam("updid") Integer id,Map res){
ModelAndView mv = new ModelAndView();
res.put("id",id);
mv.setViewName("updpage");
return mv;
}
//删除数据
//@Transactional
@RequestMapping(value = "/deleteName1")
public String deleteName(@RequestParam("delid")int id,Map res)throws Exception {
if(studentService.seleteperson(id) == null){
res.put("error", "student没有这个ID");
}else if (userService.findById(id) == null) {
res.put("error", "user没有这个ID");
}else if ((studentService.delete(id) != 1) || (userService.dele(id) != 1))
res.put("error","删除失败");
return "success";
}
//增加数据
@RequestMapping(value = "/savePerson1")
public String savePerson(@RequestParam("id") int id,
@RequestParam("username")String username,
@RequestParam("password")String password,
@RequestParam("name")String name,
@RequestParam("university")String university,Map res){
if((studentService.seleteperson(id) != null) && (userService.findById(id) != null)) {
res.put("error", "这个ID已经被占用");
}else if((studentService.save(id,name,university)!=1)||((userService.sav(id,username,password)!=1)))
res.put("error","增加数据失败");
return "success";
}
//修改数据
@RequestMapping(value = "/updaPerson1")
public String updaPerson1(@RequestParam("oldid") int oldid,
@RequestParam("id") int id,
@RequestParam("username")String username,
@RequestParam("password")String password,
@RequestParam("name")String name,
@RequestParam("university")String university,Map res){
if(studentService.seleteperson(id) != null && oldid!=id) {
res.put("error", "这个ID已经被student占用");
}else if(userService.findById(id) != null && oldid!=id){
res.put("error", "这个ID已经被user占用");
}else if((studentService.update(oldid,id,name,university)!=1)||((userService.upd(oldid,id,username,password)!=1)))
res.put("error","修改数据失败");
return "success";
}
}
@Controller
public class FindController {
ModelAndView modelAndView;
@Autowired
private UserService userService;
@Autowired
private StudentService studentService;
//主页
@RequestMapping("/aaa")
public ModelAndView insert(){
ModelAndView mv = new ModelAndView();
mv.setViewName("index.html");
return mv;
}
//查看综合数据
@RequestMapping(value = "/ifindAll")
public String find1All(Map res){
List list1 =studentService.find1all();
List list2 = userService.AllUser();
List
剩下的service,mapper,dao可以自己设置,我这里是使用xml文件进行sql操作,放在resource/mapper下了,