Spring整合Mybatis
Posted 滑稽404#
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring整合Mybatis相关的知识,希望对你有一定的参考价值。
文章目录
一、所需依赖和静态过滤
使用了properties指定版本,方便后期因为版本兼容问题而浪费时间
<properties>
<spring-version>5.3.6</spring-version>
<mybatis-version>3.5.7</mybatis-version>
<mybatis-spring-version>2.0.6</mybatis-spring-version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring-version}</version>
</dependency>
<!--AOP切面两依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-version}</version>
</dependency>
<!--切面-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<!--mysql连接驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<!--spring自己封装的jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
<!--事务依赖 Transaction -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-version}</version>
</dependency>
<!--spring整合数据层框架所需依赖 orm:持久化-->
<dependency>
<groupId>springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>1.2.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<!--静态资源过滤-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
二、db&log4j
db.properties
serverTimezone=UTC:统一时区,防止jdbc因为时间不统一报错
为什么前缀加个db.,因为dataSource有时候会识别不出username是底层的还是直接写的
这两个错误很恶心,不过挺好查的(因为遇到的人很多)
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/db5?serverTimezone=UTC
db.username=username
db.password=password
log4j.properties
网上log4j配置很多,我是博客找的
### 设置###
log4j.rootLogger = debug,stdout,D,E
### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
### 输出DEBUG 级别以上的日志到=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### 输出ERROR 级别以上的日志到=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =E://logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
三、Application
- 注册驱动管理数据源dataSource
- 注册SqlSessionFactory,需要注入dataSouce以及mybatis-config.xml和mapper
- 注册sqlSessionTemplate,根据构造器注入注入SqlSessionFactory
<!--开启注解扫描-->
<context:component-scan base-package="com.chime"/>
<!--引入外部文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!--驱动管理数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
<!--生成工厂bean:用来获取sqlSession-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/chime/dao/*Mapper.xml"/>
</bean>
<!--sqlSessionTemplate:用来注入mapper-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!--因为Mapper无法生成bean 所以建一个impl 没有自动注入需要set方法-->
<bean id="userMapper" class="com.chime.dao.UserMapperImpl">
<property name="sqlSession" ref="sqlSessionTemplate"/>
</bean>
自动扫描Dao,替代注入SqlSessionTemplate写Impl
<!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
<!--代替手动将SqlSessionTemplate注入到DaoImpl-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.chime.dao"/>
</bean>
四、mybatis-config
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<typeAliases>
<package name="com.chime.pojo"/>
</typeAliases>
五、DaoImpl
1、SqlSessionTemplate
如果使用注解自动注入了就不要再申请bean了,两个同样的bean会冲突
//@Repository("userMapper")
public class UserMapperImpl implements UserMapper{
//@Autowired
SqlSessionTemplate sqlSession;
//注入SqlSessionTemplate,用他来获取mapper
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public List<User> findAll() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.findAll();
}
}
Service层需要注入Impl
2、配置扫描Dao
@Service("bookService")
public class BookServiceImpl implements BookService {
@Autowired
private BookMapper bookMapper;
}
六、使用事务
A给B转账n元,A需要减n,B需要加n,需要两个dao方法
转账业务需要调用这两个方法,两个必须同时完成或者同时失败(事务)
1、实体类
public class Account {
private int id;
private String name;
private int money;//余额
}
2、Application
- 注册驱动管理数据源dataSource
- 注册SqlSessionFactory,需要注入dataSouce以及mybatis-config.xml和mapper
- 注册sqlSessionTemplate,根据构造器注入注入SqlSessionFactory
- 开启事务管理器
- 是否使用注解声明事务,来判断是否开启事务注解或者手动织入事务(切点和切面)
<!--开启注解扫描-->
<context:component-scan base-package="com.chime"/>
<!--引入外部文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!--spring-jdbc驱动管理数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
<!--生成工厂bean:用来获取sqlSession-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/chime/dao/*Mapper.xml"/>
</bean>
<!--sqlSessionTemplate:用来注入mapper-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<bean id="userMapper" class="com.chime.dao.UserMapperImpl">
<property name="sqlSession" ref="sqlSessionTemplate"/>
</bean>
<!--开启事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--开启事务注解-->
<!--<tx:annotation-driven transaction-manager="transactionManager"/>-->
<!--配置通知-->
<tx:advice id="accountAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置切面-->
<aop:config>
<aop:pointcut id="accountPoint" expression="execution(* com.chime.dao.*.*(..))"/>
<aop:advisor advice-ref="accountAdvice" pointcut-ref="accountPoint"/>
</aop:config>
3、mapper和Impl
注解声明组件
自动注入SqlSessionTemplate
@Repository("accountMapper")
public class AccountMapperImpl implements AccountMapper{
@Autowired
SqlSessionTemplate sqlSession;
@Override
public List<Account> getAllAccount() {
AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
return mapper.getAllAccount();
}
@Override
public in以上是关于Spring整合Mybatis的主要内容,如果未能解决你的问题,请参考以下文章
请教mybatis+spring+atomikos的整合问题
基于Spring+SpringMVC+MyBatis开发书评网Spring和MyBatis的整合