跳转到内容
主菜单
主菜单
移至侧栏
隐藏
导航
首页
最近更改
随机页面
MediaWiki帮助
代码酷
搜索
搜索
中文(中国大陆)
外观
创建账号
登录
个人工具
创建账号
登录
未登录编辑者的页面
了解详情
贡献
讨论
编辑“︁
Spring整合MyBatis
”︁(章节)
页面
讨论
大陆简体
阅读
编辑
编辑源代码
查看历史
工具
工具
移至侧栏
隐藏
操作
阅读
编辑
编辑源代码
查看历史
常规
链入页面
相关更改
特殊页面
页面信息
外观
移至侧栏
隐藏
您的更改会在有权核准的用户核准后向读者展示。
警告:
您没有登录。如果您进行任何编辑,您的IP地址会公开展示。如果您
登录
或
创建账号
,您的编辑会以您的用户名署名,此外还有其他益处。
反垃圾检查。
不要
加入这个!
= Spring整合MyBatis = == 简介 == '''Spring整合MyBatis'''是指通过Spring框架提供的依赖注入和事务管理能力,与MyBatis持久层框架进行无缝集成。这种整合方式允许开发者利用MyBatis的SQL映射灵活性,同时享受Spring的声明式事务管理和松耦合优势。主要整合组件包括: * '''SqlSessionFactoryBean''':创建MyBatis的SqlSessionFactory * '''MapperScannerConfigurer''':自动扫描并注册Mapper接口 * '''@MapperScan'''注解:替代XML配置的扫描方式 == 整合原理 == <mermaid> graph LR A[Spring容器] --> B[SqlSessionFactoryBean] B --> C[DataSource] A --> D[MapperScannerConfigurer] D --> E[Mapper接口代理对象] A --> F[Spring事务管理器] F --> C </mermaid> 整合的核心是通过Spring的IoC容器管理MyBatis的核心组件,实现: 1. 数据源(DataSource)由Spring管理 2. SqlSessionFactory通过Spring配置 3. Mapper接口自动注入 == 配置方式 == === XML配置方式 === 传统配置方式,适用于Spring 3.x及早期版本: <syntaxhighlight lang="xml"> <!-- 数据源配置 --> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test"/> <property name="username" value="root"/> <property name="password" value="password"/> </bean> <!-- MyBatis-Spring整合 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mapperLocations" value="classpath*:mapper/*.xml"/> </bean> <!-- Mapper扫描 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.example.dao"/> </bean> </syntaxhighlight> === Java配置方式 === Spring 4+推荐的方式: <syntaxhighlight lang="java"> @Configuration @MapperScan("com.example.dao") public class MyBatisConfig { @Bean public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/test"); dataSource.setUsername("root"); dataSource.setPassword("password"); return dataSource; } @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dataSource()); factoryBean.setMapperLocations( new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml")); return factoryBean.getObject(); } } </syntaxhighlight> == 事务管理 == Spring提供声明式事务管理,与MyBatis整合后可通过注解控制事务: <syntaxhighlight lang="java"> @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Transactional @Override public void createUser(User user) { userMapper.insert(user); // 其他数据库操作 } } </syntaxhighlight> 关键点: * 需要在配置类添加<code>@EnableTransactionManagement</code> * 事务管理器需使用<code>DataSourceTransactionManager</code> == 实际案例 == 电商系统中的订单处理场景: <syntaxhighlight lang="java"> @Repository public interface OrderMapper { @Insert("INSERT INTO orders(order_id, user_id, amount) VALUES(#{orderId}, #{userId}, #{amount})") int insert(Order order); @Update("UPDATE inventory SET stock = stock - #{quantity} WHERE product_id = #{productId}") int reduceStock(@Param("productId") Long productId, @Param("quantity") int quantity); } @Service public class OrderService { @Autowired private OrderMapper orderMapper; @Transactional public void placeOrder(Order order, List<OrderItem> items) { orderMapper.insert(order); items.forEach(item -> { orderMapper.reduceStock(item.getProductId(), item.getQuantity()); }); } } </syntaxhighlight> == 常见问题 == === 类型别名处理 === 可通过以下方式配置: <syntaxhighlight lang="java"> @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); //... factoryBean.setTypeAliasesPackage("com.example.model"); return factoryBean.getObject(); } </syntaxhighlight> === 多数据源配置 === 需要为每个数据源创建独立的配置: <syntaxhighlight lang="java"> @Configuration @MapperScan(basePackages = "com.example.primary", sqlSessionFactoryRef = "primarySqlSessionFactory") public class PrimaryDataSourceConfig { // 主数据源配置... } @Configuration @MapperScan(basePackages = "com.example.secondary", sqlSessionFactoryRef = "secondarySqlSessionFactory") public class SecondaryDataSourceConfig { // 从数据源配置... } </syntaxhighlight> == 性能优化 == 1. '''批量操作''':使用<code>SqlSessionTemplate</code>的批量模式 2. '''二级缓存''':在Mapper XML中配置<cache/>标签 3. '''延迟加载''':在MyBatis配置中设置<code>lazyLoadingEnabled=true</code> == 最佳实践 == * 始终使用接口绑定方式(Mapper接口) * 生产环境使用连接池(如HikariCP) * 复杂的SQL写在XML中,简单CRUD可使用注解 * 事务边界应定义在Service层 == 数学表示 == 事务的ACID特性可以用以下公式表示: <math> \begin{cases} \text{原子性}(A): \forall o \in O, \text{要么全部执行} \Phi(o), \text{要么全部回滚} \\ \text{一致性}(C): \Phi(S_{\text{pre}}) = S_{\text{post}} \\ \text{隔离性}(I): \Phi_1 \parallel \Phi_2 \Rightarrow \Phi_1(S) \cap \Phi_2(S) = \emptyset \\ \text{持久性}(D): \text{一旦提交}, \forall t > t_{\text{commit}}, S_t \text{保持提交状态} \end{cases} </math> 其中<math>\Phi</math>表示事务操作,<math>S</math>表示系统状态。 [[Category:后端框架]] [[Category:Spring]] [[Category:Spring ORM整合]]
摘要:
请注意,所有对代码酷的贡献均被视为依照知识共享署名-非商业性使用-相同方式共享发表(详情请见
代码酷:著作权
)。如果您不希望您的文字作品被随意编辑和分发传播,请不要在此提交。
您同时也向我们承诺,您提交的内容为您自己所创作,或是复制自公共领域或类似自由来源。
未经许可,请勿提交受著作权保护的作品!
取消
编辑帮助
(在新窗口中打开)