MyBatis-Spring整理(一)

1、建立一個maven項目(略)

2、添加依賴關係

1         <dependency>
2             <groupId>org.mybatis</groupId>
3             <artifactId>mybatis</artifactId>
4         </dependency>
5         <dependency>
6             <groupId>org.mybatis</groupId>
7             <artifactId>mybatis-spring</artifactId>
8         </dependency>

3、注入spring上下文

    <!-- SqlSessionFactoryBean 是用於建立 SqlSessionFactory  -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath*:mybatis/SUserMapper.xml" />
    </bean>

4、定義user接口

1 public interface SUserMapper {
2 
3     @Select("SELECT * FROM S_USER")
4     List<SUser> getAllUserList();
5 
6 }

5、把接口注入spring

    <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="com.unis.synchron.dao.SUserMapper" />
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>

或者html

1     <!-- 自動掃描com.unis.synchron.dao下的全部接口,而後建立各自接口的動態代理類 -->
2     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
3         <property name="basePackage" value="com.unis.synchron.dao"/>
4         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
5     </bean>

6、接口測試

 1 @RunWith(SpringJUnit4ClassRunner.class)
 2 @ContextConfiguration(locations = { "classpath*:spring/*.xml" })
 3 public class SUserMapperTest extends AbstractJUnit4SpringContextTests {
 4 
 5     @Autowired
 6     private SUserMapper userMapper;
 7 
 8     @Test
 9     public void testGetAllUserList() {
10         List<SUser> users = userMapper.getAllUserList();
11         for (SUser user : users) {
12             System.out.println(user.toString());
13         }
14     }
15 }

本文根據http://www.mybatis.org/spring/zh/index.html進行整理。spring

相關文章
相關標籤/搜索