首页 > 其他分享 >七、Spring整合MyBatis

七、Spring整合MyBatis

时间:2023-02-21 17:14:36浏览次数:39  
标签:Mapper Service Spring 整合 accountMapper MyBatis save public

整合思路

image

将SqlSessionFactory配置到Spring容器中

<!--加载jdbc.properties-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
	<property name="driverClass" value="${jdbc.driver}"/>
	<property name="jdbcUrl" value="${jdbc.url}"/>
	<property name="user" value="${jdbc.username}"/>
	<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置MyBatis的SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	<property name="dataSource" ref="dataSource"/>
	<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
</bean>

扫描Mapper,让Spring容器产生Mapper实现类

<!--配置Mapper扫描-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.study.mapper"/>
</bean>

配置声明式事务控制

<!--配置声明式事务控制-->
<bean id="transacionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 <property name="dataSource" ref="dataSource"/>
</bean>

<tx:advice id="txAdvice" transaction-manager="transacionManager">
	<tx:attributes>
	<tx:method name="*"/>
	</tx:attributes>
</tx:advice>

<aop:config>
	<aop:pointcut id="txPointcut" expression="execution(* com.study.service.impl.*.*(..))"/>
	<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>

修改Service实现类代码

@Service("accountService")
public class AccountServiceImpl implements AccountService {
  @Autowired
  private AccountMapper accountMapper;

  public void save(Account account) {
  	accountMapper.save(account);
  }

  public List<Account> findAll() {
  	return accountMapper.findAll();
  }
}

标签:Mapper,Service,Spring,整合,accountMapper,MyBatis,save,public
From: https://www.cnblogs.com/yellow-mokey/p/17141612.html

相关文章