现在MyBatis和Spring有了,现在到了把MyBatis整合到Spring里的时候了。
spring-MyBatis的官方文档
1:Maven导入依赖包
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.22</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${springVersion}</version>
</dependency>
2:在beans.xml
增加如下
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="12345678"/>
<property name="driver">
<bean class="com.mysql.cj.jdbc.Driver"/>
</property>
</bean>
<bean id="accountDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.ppf.dao.IAccountDao"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
3:怎么用?
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
IAccountDao dao = context.getBean("accountDao", IAccountDao.class);
List<Account> accounts = dao.fetchSomeAccounts(0, 2);