springboot2 多模块项目中mybatis如何使用

发布时间:2021-07-08 16:33:35 作者:Leah
来源:亿速云 阅读:351
# SpringBoot2 多模块项目中MyBatis如何使用

## 一、多模块项目基础概念

### 1.1 什么是多模块项目
多模块项目(Multi-Module Project)是通过Maven或Gradle构建工具将一个大型项目拆分为多个相互关联的子模块的工程结构。每个模块可以独立编译、测试和打包,同时保持项目间的依赖关系。

**典型的多模块结构:**

parent-project(父工程) ├── pom.xml ├── module-common(公共模块) ├── module-dao(数据访问层) ├── module-service(业务逻辑层) └── module-web(Web表现层)


### 1.2 多模块的优势
1. **代码复用**:公共代码可提取到独立模块
2. **职责分离**:各层模块职责明确
3. **构建效率**:可单独编译修改的模块
4. **依赖管理**:统一管理依赖版本

## 二、创建SpringBoot多模块项目

### 2.1 初始化父工程
```xml
<!-- parent pom.xml -->
<groupId>com.example</groupId>
<artifactId>multi-module-demo</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>

<modules>
    <module>module-common</module>
    <module>module-dao</module>
    <module>module-service</module>
    <module>module-web</module>
</modules>

2.2 配置SpringBoot依赖管理

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.3</version>
    <relativePath/>
</parent>

三、MyBatis基础集成

3.1 添加核心依赖

module-dao中引入:

<dependencies>
    <!-- MyBatis Starter -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.2</version>
    </dependency>
    
    <!-- 数据库驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

3.2 基础配置

application.yml配置示例:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/demo?useSSL=false
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.model

四、多模块中的MyBatis特殊配置

4.1 模块间依赖关系

确保依赖传递:

<!-- module-service/pom.xml -->
<dependencies>
    <dependency>
        <groupId>com.example</groupId>
        <artifactId>module-dao</artifactId>
        <version>${project.version}</version>
    </dependency>
</dependencies>

4.2 扫描路径问题解决

方案1:主模块添加扫描注解

@SpringBootApplication(scanBasePackages = "com.example")
@MapperScan("com.example.dao")
public class WebApplication {
    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class, args);
    }
}

方案2:每个模块单独配置

// 在dao模块配置类
@Configuration
@MapperScan("com.example.dao")
public class MyBatisConfig {}

4.3 XML映射文件路径处理

推荐结构:

module-dao
├── src/main/java
│   └── com/example/dao
└── src/main/resources
    └── mapper
        └── UserMapper.xml

配置示例:

mybatis:
  mapper-locations: classpath*:mapper/**/*.xml

五、高级功能实现

5.1 多数据源配置

@Configuration
@MapperScan(basePackages = "com.example.db1.dao", 
           sqlSessionFactoryRef = "db1SqlSessionFactory")
public class Db1DataSourceConfig {
    
    @Bean
    @ConfigurationProperties("spring.datasource.db1")
    public DataSource db1DataSource() {
        return DataSourceBuilder.create().build();
    }
    
    @Bean
    public SqlSessionFactory db1SqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(db1DataSource());
        return factoryBean.getObject();
    }
}

5.2 动态数据源切换

实现AbstractRoutingDataSource:

public class DynamicDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceContextHolder.getDataSourceType();
    }
}

5.3 自定义TypeHandler

@MappedTypes(Enum.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class EnumTypeHandler<E extends Enum<E>> 
       extends BaseTypeHandler<E> {
       
    private Class<E> type;
    
    public EnumTypeHandler(Class<E> type) {
        this.type = type;
    }
    
    // 实现抽象方法...
}

六、最佳实践与常见问题

6.1 推荐的项目结构

multi-module-demo
├── module-common
│   ├── 通用工具类
│   └── 基础DTO
├── module-dao
│   ├── entity
│   ├── mapper
│   └── repository
├── module-service
│   ├── service
│   └── impl
└── module-web
    ├── controller
    ├── dto
    └── config

6.2 性能优化建议

  1. 启用二级缓存:mybatis.configuration.cache-enabled=true
  2. 批量操作使用SqlSessionTemplate
  3. 合理设置连接池参数

6.3 常见问题解决

问题1:Mapper接口无法注入 - 检查@MapperScan包路径是否正确 - 确认mapper接口有@Mapper注解或XML对应

问题2:XML映射未生效 - 检查mapper-locations配置 - 确认XML文件名与接口名一致

问题3:多模块事务失效 - 确保@Transactional注解在公共模块 - 主模块添加@EnableTransactionManagement

七、完整示例代码结构

7.1 关键代码示例

实体类:

// module-dao/src/main/java/com/example/entity/User.java
@Data
public class User {
    private Long id;
    private String username;
    private LocalDateTime createTime;
}

Mapper接口:

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM user WHERE id = #{id}")
    User selectById(Long id);
    
    @Insert("INSERT INTO user(username) VALUES(#{username})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(User user);
}

Service实现:

// module-service/src/main/java/com/example/service/impl/UserServiceImpl.java
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    
    private final UserMapper userMapper;
    
    @Override
    @Transactional
    public Long createUser(String username) {
        User user = new User();
        user.setUsername(username);
        userMapper.insert(user);
        return user.getId();
    }
}

八、总结

在SpringBoot2多模块项目中使用MyBatis需要注意: 1. 模块划分:清晰界定各模块职责 2. 依赖管理:统一管理MyBatis相关依赖版本 3. 扫描配置:正确处理跨模块的组件扫描 4. 资源文件:合理规划XML映射文件位置 5. 事务管理:确保跨模块事务生效

通过本文介绍的方式,可以构建出结构清晰、易于维护的SpringBoot多模块MyBatis应用。实际开发中应根据项目规模灵活调整模块划分方案。

提示:本文基于SpringBoot 2.7.x和MyBatis 3.5.x版本,不同版本配置可能存在差异 “`

该文章包含约2700字,采用Markdown格式编写,涵盖了从多模块项目创建到MyBatis集成的完整流程,包含代码示例、配置建议和常见问题解决方案。文章结构清晰,适合作为技术文档参考。

推荐阅读:
  1. SpringBoot2 配置多数据源,整合MybatisPlus增强插件
  2. SpringBoot2整合dubbo使用Zookeeper作为注册中心,使用yml配置

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot2 mybatis

上一篇:springboot中spock如何使用

下一篇:springboot项目中怎么使用springload实现热部署

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》