20. 从零开始学springboot-搭建一个可以上线的项目结构-单项目篇(1)

前言

通过前面的多章学习,相信大家对于springboot整合各个基础依赖已经得心应手了。并且,对于各个依赖的选择和使用都有了一定的理解。本章,将对前段时间的所学做一个总结,会完成一个可以上生产的项目基础架构。
首先,我们来归纳一下一般项目的需求:

  • 多数据源
  • 多数据源分布式事务
  • druid数据源监控
  • 数据持久层
  • 缓存
  • 日志记录

以上需求基本囊括了所有项目的基础。那么我们,根据需求,对应我们的前几章所学,不难得出springboot+mybatis+多数据源+druid+atomikos+redis+log的搭配,另外,项目多环境的情况,还必须提供切换环境的配置。为了解决mybatis写entity个mapper.xml文件麻烦的问题,我们需要引入自动生成插件mybatis-generator。

创建空项目

20. 从零开始学springboot-搭建一个可以上线的项目结构-单项目篇(1)_第1张图片
1.png

添加依赖


        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.0.0
        
        
            com.alibaba
            druid-spring-boot-starter
            1.1.16
        
        
        
            org.springframework.boot
            spring-boot-starter-jta-atomikos
        
        
        
            mysql
            mysql-connector-java
            8.0.11
        
        
        
            com.google.guava
            guava
            18.0
        
        
        
            org.springframework.boot
            spring-boot-starter-aop
        
        
        
            org.springframework.boot
            spring-boot-starter-redis
            1.4.7.RELEASE
        
        
20. 从零开始学springboot-搭建一个可以上线的项目结构-单项目篇(1)_第2张图片
4.png

完善plugin信息

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            

            
            
                org.mybatis.generator
                mybatis-generator-maven-plugin
                1.3.2
                
                    
                    src/main/resources/generator/masterGenerator.xml
                    
                    true
                    true
                
            
        
    
20. 从零开始学springboot-搭建一个可以上线的项目结构-单项目篇(1)_第3张图片
5.png

添加配置

application.yml:

## 公共配置start
## 配置数据源相关信息
spring:
  ## 环境配置
  profiles:
    active: dev
  ## 数据源设置
  datasource:
    type: com.alibaba.druid.pool.xa.DruidXADataSource
    druid:
      ## 连接池配置
      master:
        ## JDBC配置
        name: master
        url: jdbc:mysql://192.168.145.131:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
        username: root
        password: 123456
        driver-class-name: com.mysql.cj.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: true
        testOnReturn: true
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20
      slave:
        ## JDBC配置
        name: slave
        url: jdbc:mysql://192.168.145.131/test2?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
        username: root
        password: 123456
        driver-class-name: com.mysql.cj.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: true
        testOnReturn: true
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20

  redis:
    host: 127.0.0.1  # redis服务所在的地址
    port: 6379
    password:   # redis的密码默认为空
    pool:
      max-active: 8  #连接池最大连接数(使用负值表示没有限制)
      max-idle: 8  #连接池最大空闲数
      min-idle: 1  #连接池最小空闲数
      max-wait: 60000  #获取连接的超时等待事件
    timeout: 30000  #连接redis服务器的最大等待时间

  #druid监控页面用户名和密码
  druid:
    name: admin
    pass: admin

## 该配置节点为独立的节点
mybatis:
  mapper-locations: classpath:mapper/*/*.xml  # 注意:一定要对应mapper映射xml文件的所在路径
  type-aliases-package: com.mrcoder.sbmmultidbxmldruidatomikos.entity # 注意:对应实体类的路径
  configuration:
    map-underscore-to-camel-case: true

## 公共配置 end
---
## 开发环境配置
spring:
  profiles: dev
server:
  port: 8080
---
## 测试环境配置
spring:
  profiles: test
server:
  port: 8082
---
## 生产环境配置
spring:
  profiles: prod
server:
  port: 8084

建库

创建test、test2库
test:

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `age` int(11) NOT NULL,
  `grade` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

test2:

CREATE TABLE `teacher` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `age` int(11) NOT NULL,
  `course` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

完善

目录结构


20. 从零开始学springboot-搭建一个可以上线的项目结构-单项目篇(1)_第4张图片
2.png

20. 从零开始学springboot-搭建一个可以上线的项目结构-单项目篇(1)_第5张图片
3.png

根据目录结构,请自行创建package和class。

config/datasource/DataSourceConfig

package com.mrcoder.sbmmultidbxmldruidatomikos.config.datasource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import javax.sql.DataSource;
import java.util.Properties;
/**
 * 数据源配置类
 */
@Configuration
public class DataSourceConfig {
    @Autowired
    private Environment env;
    @Value("${spring.datasource.type}")
    private String dataSourceType;
    /**
     * 配置主数据源,多数据源中必须要使用@Primary指定一个主数据源
     * 其次DataSource里用的是DruidXADataSource ,而后注册到AtomikosDataSourceBean并且返回
     */
    @Primary
    @Bean(name = "masterDataSource")
    public DataSource masterDataSource() {
        AtomikosDataSourceBean ds = new AtomikosDataSourceBean();
        Properties prop = build(env, "spring.datasource.druid.master.");
        ds.setXaDataSourceClassName(dataSourceType);
        ds.setPoolSize(5);
        ds.setXaProperties(prop);
        return ds;
    }
    /**
     * 配置次数据源
     * 其次DataSource里用的是DruidXADataSource ,而后注册到AtomikosDataSourceBean并且返回
     */
    @Bean(name = "slaveDataSource")
    public DataSource slaveDataSource() {
        AtomikosDataSourceBean ds = new AtomikosDataSourceBean();
        Properties prop = build(env, "spring.datasource.druid.slave.");
        ds.setXaDataSourceClassName(dataSourceType);
        ds.setPoolSize(5);
        ds.setXaProperties(prop);
        return ds;
    }
    private Properties build(Environment env, String prefix) {
        Properties prop = new Properties();
        prop.put("name", env.getProperty(prefix + "name"));
        prop.put("url", env.getProperty(prefix + "url"));
        prop.put("username", env.getProperty(prefix + "username"));
        prop.put("password", env.getProperty(prefix + "password"));
        prop.put("driverClassName", env.getProperty(prefix + "driverClassName", ""));
        prop.put("filters", env.getProperty(prefix + "filters"));
        prop.put("maxActive", env.getProperty(prefix + "maxActive", Integer.class));
        prop.put("initialSize", env.getProperty(prefix + "initialSize", Integer.class));
        prop.put("maxWait", env.getProperty(prefix + "maxWait", Integer.class));
        prop.put("minIdle", env.getProperty(prefix + "minIdle", Integer.class));
        prop.put("timeBetweenEvictionRunsMillis",
                env.getProperty(prefix + "timeBetweenEvictionRunsMillis", Integer.class));
        prop.put("minEvictableIdleTimeMillis", env.getProperty(prefix + "minEvictableIdleTimeMillis", Integer.class));
        prop.put("validationQuery", env.getProperty(prefix + "validationQuery"));
        prop.put("testWhileIdle", env.getProperty(prefix + "testWhileIdle", Boolean.class));
        prop.put("testOnBorrow", env.getProperty(prefix + "testOnBorrow", Boolean.class));
        prop.put("testOnReturn", env.getProperty(prefix + "testOnReturn", Boolean.class));
        prop.put("poolPreparedStatements", env.getProperty(prefix + "poolPreparedStatements", Boolean.class));
        prop.put("maxOpenPreparedStatements", env.getProperty(prefix + "maxOpenPreparedStatements", Integer.class));
        return prop;
    }
}

config/datasource/MasterSqlSessionTemplateConfig

package com.mrcoder.sbmmultidbxmldruidatomikos.config.datasource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
/**
 * MasterSqlSessionTemplateConfig配置类
 */
@Configuration
//下面的sqlSessionTemplateRef 值需要和生成的SqlSessionTemplate bean name相同,如果没有指定name,那么就是方法名
@MapperScan(basePackages = {"com.mrcoder.sbmmultidbxmldruidatomikos.mapper.master"}, sqlSessionTemplateRef = "masterSqlSessionTemplate")
public class MasterSqlSessionTemplateConfig {
    @Value("${mybatis.mapper-locations}")
    private String mapper_location;
    @Value("${mybatis.type-aliases-package}")
    private String type_aliases_package;
    @Value("${mybatis.configuration.map-underscore-to-camel-case}")
    private boolean mapUnderscoreToCamelCase;
    //将MybatisConfig类中初始化的对象注入进来
    @Autowired
    private ConfigurationCustomizer customizer;
    private Logger logger = LoggerFactory.getLogger(MasterSqlSessionTemplateConfig.class);
    /**
     * 自定义sqlSessionFactory配置(因为没有用到MybatisAutoConfiguration自动配置类,需要手动配置)
     */
    @Bean
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
        logger.info("mapper文件地址为:{}", mapper_location);
        //在基本的 MyBatis 中,session 工厂可以使用 SqlSessionFactoryBuilder 来创建。
        //而在 MyBatis-spring 中,则使用SqlSessionFactoryBean 来替代:
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //如果重写了 SqlSessionFactory 需要在初始化的时候手动将 mapper 地址 set到 factory 中,否则会报错:
        //org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapper_location));
        //下面这个setTypeAliasesPackage无效,是mybatis集成springBoot的一个bug,暂时未能解决
        bean.setTypeAliasesPackage(type_aliases_package);
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        logger.info("mybatis配置驼峰转换为:{}", mapUnderscoreToCamelCase);
        configuration.setMapUnderscoreToCamelCase(mapUnderscoreToCamelCase);
        //因为没有用mybatis-springBoot自动装配,所以需要手动将configuration装配进去,要不然自定义的map key驼峰转换不起作用
        customizer.customize(configuration);
        bean.setConfiguration(configuration);
        return bean.getObject();
    }
    /**
     * SqlSessionTemplate 是 SqlSession接口的实现类,是spring-mybatis中的,实现了SqlSession线程安全
     */
    @Bean
    public SqlSessionTemplate masterSqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
        return template;
    }
}

config/datasource/SlaveSqlSessionTemplateConfig

package com.mrcoder.sbmmultidbxmldruidatomikos.config.datasource;
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.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
/**
 * SlaveSqlSessionTemplateConfig配置类
 */
@Configuration
@MapperScan(basePackages = {"com.mrcoder.sbmmultidbxmldruidatomikos.mapper.slave"}, sqlSessionTemplateRef = "slaveSqlSessionTemplate")
public class SlaveSqlSessionTemplateConfig {
    @Value("${mybatis.mapper-locations}")
    private String mapper_location;
    @Bean
    public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("slaveDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //如果重写了 SqlSessionFactory 需要在初始化的时候手动将 mapper 地址 set到 factory 中,否则会报错:
        //org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapper_location));
        return bean.getObject();
    }
    @Bean
    public SqlSessionTemplate slaveSqlSessionTemplate(@Qualifier("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
        return template;
    }
}

config/datasource/TransactionManagerConfig

package com.mrcoder.sbmmultidbxmldruidatomikos.config.datasource;
import com.atomikos.icatch.jta.UserTransactionImp;
import com.atomikos.icatch.jta.UserTransactionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.jta.JtaTransactionManager;
import javax.transaction.UserTransaction;
/**
 * 多数据源事务管理器配置类
 */
@Configuration
public class TransactionManagerConfig {
    /**
     * 分布式事务使用JTA管理,不管有多少个数据源只要配置一个 JtaTransactionManager
     * @return
     */
    @Bean
    public JtaTransactionManager transactionManager(){
        UserTransactionManager userTransactionManager = new UserTransactionManager();
        UserTransaction userTransaction = new UserTransactionImp();
        return new JtaTransactionManager(userTransaction, userTransactionManager);
    }
}

config/wrapper/CustomWrapper

package com.mrcoder.sbmmultidbxmldruidatomikos.config.wrapper;
import com.google.common.base.CaseFormat;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.wrapper.MapWrapper;
import java.util.Map;
/**
 * @Description: 自定义wrapper处理spring boot + mybatis返回结果为map时的key值转换为驼峰
 */
public class CustomWrapper extends MapWrapper {
    public CustomWrapper(MetaObject metaObject, Map map) {
        super(metaObject, map);
    }
    @Override
    public String findProperty(String name, boolean useCamelCaseMapping) {
        if (useCamelCaseMapping) {
            return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name);
        }
        return name;
    }
}

config/wrapper/MapWrapperFactory

package com.mrcoder.sbmmultidbxmldruidatomikos.config.wrapper;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.wrapper.ObjectWrapper;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import java.util.Map;
/**
 * 实现接口 ObjectWrapperFactory,通过包装工厂来创建自定义的wrapper
 */
public class MapWrapperFactory implements ObjectWrapperFactory {
    @Override
    public boolean hasWrapperFor(Object object) {
        return object != null && object instanceof Map;
    }
    @Override
    public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
        return new CustomWrapper(metaObject, (Map) object);
    }
}

config/DruidConfig

package com.mrcoder.sbmmultidbxmldruidatomikos.config;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * 配置 Druid登陆配置(白名单等)
 */
@Configuration
public class DruidConfig {
    @Value("${spring.druid.name}")
    private String name;
    @Value("${spring.druid.pass}")
    private String pass;
    private Logger logger = LoggerFactory.getLogger(DruidConfig.class);
    /**
     * 配置 Druid控制台 白名单、黑名单、用户名、密码等
     * 访问地址  ip+port/projectContextPath/druid/index.html
     */
    @Bean
    public ServletRegistrationBean DruidStatViewServlet(){
        logger.info("servletRegistrationBean configure is starting...");
        //org.springframework.boot.context.embedded.ServletRegistrationBean提供类的进行注册.
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
        //添加初始化参数
        servletRegistrationBean.addInitParameter("allow","*");
        servletRegistrationBean.addInitParameter("loginUsername", name);
        servletRegistrationBean.addInitParameter("loginPassword", pass);
        //是否可以重置
        servletRegistrationBean.addInitParameter("resetEnable","false");
        return servletRegistrationBean;
    }
    /**
     * 注册一个:filterRegistrationBean
     */
    @Bean
    public FilterRegistrationBean druidStatFilter2(){
        logger.info("filterRegistrationBean configure is starting...");
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        //添加过滤规则.
        filterRegistrationBean.addUrlPatterns("/*");
        //添加不需要忽略的格式信息.
       filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}

config/MybatisConfig

package com.mrcoder.sbmmultidbxmldruidatomikos.config;
import com.mrcoder.sbmmultidbxmldruidatomikos.config.wrapper.MapWrapperFactory;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * mybatis配置类,将自定义的MapWrapperFactory覆盖默认的ObjectWrapperFactory
 */
@Configuration
public class MybatisConfig {
    private Logger logger = LoggerFactory.getLogger(MybatisConfig.class);
    @Bean
    public ConfigurationCustomizer mybatisConfigurationCustomizer() {
        logger.info("initialize the ConfigurationCustomizer....");
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                configuration.setObjectWrapperFactory(new MapWrapperFactory());
            }
        };
    }
}

config/RedisConfig

package com.mrcoder.sbmmultidbxmldruidatomikos.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mrcoder.sbmmultidbxmldruidatomikos.utils.redis.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
 * @redis 配置类
 */
@Configuration
public class RedisConfig {
    private Logger logger = LoggerFactory.getLogger(RedisConfig.class);
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);
        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();
        return template;
    }
    /**
     * 对hash类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public HashOperations hashOperations(RedisTemplate redisTemplate) {
        return redisTemplate.opsForHash();
    }
    /**
     * 对redis字符串类型数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ValueOperations valueOperations(RedisTemplate redisTemplate) {
        return redisTemplate.opsForValue();
    }
    /**
     * 对链表类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ListOperations listOperations(RedisTemplate redisTemplate) {
        return redisTemplate.opsForList();
    }
    /**
     * 对无序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public SetOperations setOperations(RedisTemplate redisTemplate) {
        return redisTemplate.opsForSet();
    }
    /**
     * 对有序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ZSetOperations zSetOperations(RedisTemplate redisTemplate) {
        return redisTemplate.opsForZSet();
    }
    /**
     * 使用上面初始化的RedisTemplate实例来初始化一个RedisUtil对象
     * ps:@Qualifier("redisTemplate") 可以不用加,如果存在RedisTemplate实例,spring会默认注入
     */
    @Bean
    public RedisUtil redisUtil(@Qualifier("redisTemplate") RedisTemplate redisTemplate) {
        RedisUtil redisUtil = new RedisUtil();
        redisUtil.setRedisTemplate(redisTemplate);
        return redisUtil;
    }
}

entity/master/Student

package com.mrcoder.sbmmultidbxmldruidatomikos.entity.master;
import java.io.Serializable;
public class Student implements Serializable {
    private Long id;
    private String name;
    private int age;
    private int grade;
    public Student() {
    }
    public Student(String name, int age, int grade) {
        this.name = name;
        this.age = age;
        this.grade = grade;
    }
    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", grade=" + grade +
                '}';
    }
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public int getGrade() {
        return grade;
    }
    public void setGrade(int grade) {
        this.grade = grade;
    }
}

entity/slave/Teacher

package com.mrcoder.sbmmultidbxmldruidatomikos.entity.slave;
import java.io.Serializable;
public class Teacher implements Serializable {
    private Long id;
    private String name;
    private int age;
    private int course;
    public Teacher() {
    }
    public Teacher(String name, int age, int course) {
        this.name = name;
        this.age = age;
        this.course = course;
    }
    @Override
    public String toString() {
        return "Teacher{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age='" + age + '\'' +
                ", course='" + course + '\'' +
                '}';
    }
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public int getCourse() {
        return course;
    }
    public void setCourse(int course) {
        this.course = course;
    }
}

mapper/master/StudentMapper

package com.mrcoder.sbmmultidbxmldruidatomikos.mapper.master;
import com.mrcoder.sbmmultidbxmldruidatomikos.entity.master.Student;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface StudentMapper {
    //    @Select("SELECT * FROM student")
    List getList();

    //    @Select("SELECT * FROM student WHERE id = #{id}")
    Student getById(Long id);

    //    @Insert("INSERT INTO student(age,grade,name) VALUES(#{age}, #{grade}, #{name})")
    Integer insert(Student student);

    //    @Update("UPDATE student SET name=#{name},age=#{age}, grade=#{grade} WHERE id =#{id}")
    Integer update(Student student);

    //    @Delete("DELETE FROM student WHERE id =#{id}")
    Integer delete(Long id);


    //注解方式,本项目不建议使用
    @Select("SELECT * FROM student")
    List getListByAnno();
}

mapper/master/TeacherMapper

package com.mrcoder.sbmmultidbxmldruidatomikos.mapper.slave;
import com.mrcoder.sbmmultidbxmldruidatomikos.entity.slave.Teacher;
import java.util.List;
public interface TeacherMapper {
    //    @Select("SELECT * FROM teacher")
    List getList();

    //    @Select("SELECT * FROM teacher WHERE id = #{id}")
    Teacher getById(Long id);

    //    @Insert("INSERT INTO teacher(age,course,name) VALUES(#{age}, #{course}, #{name})")
    void insert(Teacher teacher);

    //    @Update("UPDATE teacher SET name=#{name},age=#{age}, course=#{course} WHERE id =#{id}")
    void update(Teacher teacher);

    //    @Delete("DELETE FROM teacher WHERE id =#{id}")
    void delete(Long id);
}

受制于篇幅限制

请查看下章 从零开始学springboot-搭建一个可以上线的项目结构-单项目篇(2)

项目地址

https://github.com/MrCoderStack/SpringBootDemo/tree/master/sbm-multidb-xml-druid-atomikos

https://gitee.com/MrCoderStack/SpringBootDemo/tree/master/sbm-multidb-xml-druid-atomikos

请关注我的订阅号

订阅号.png

你可能感兴趣的:(20. 从零开始学springboot-搭建一个可以上线的项目结构-单项目篇(1))