关于整合spring+mybatis 第三种方式-使用注解

使用注解

1.与前两种方法一致。不过稍许不同的是beans.xml中配置的差异。

<!-- 配置sqlSessionFactory -->
     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
         <property name="dataSource" ref="dataSource"></property>
         <property name="configLocation" value="classpath:com/bsss/conf/mybatis.xml"></property>
     </bean>
    
    <!-- id="userloginMapper"必须与services实现类中所声明的mapper变量名保持一致 -->
    <bean id="userloginMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="com.bsss.mapper.UserloginMapper"></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>
    <bean id="userServices" class="com.bsss.services.impl.UserLoginServicesImpl">
        <property name="userloginMapper" ref="userloginMapper"></property>
    </bean>

2. 增加Mapper接口

//Mapper接口
public interface UserloginMapper {
    //org.mybatis.spring.mapper.MapperFactoryBean
    @Select("select * from userlogin")
    public List<Userlogin> getUserlogin();
}

3. Services层接口和实现类

public interface UserLoginServices {
    public List<Userlogin> getUserLoginInfo();
}


public class UserLoginServicesImpl implements UserLoginServices {
    private UserloginMapper userloginMapper;//必须与beans.xml中mapper的bean id保持一致
    //必须有setter方法
    public void setUserloginMapper(UserloginMapper userloginMapper) {
        this.userloginMapper = userloginMapper;
    }
    @Override
    public List<Userlogin> getUserLoginInfo() {
        // TODO Auto-generated method stub
        return userloginMapper.getUserlogin();
    }
    
}

4. 测试类

public class Test {

    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("com/bsss/conf/beans.xml");
        UserLoginServices uls = (UserLoginServices)ac.getBean("userServices");
        System.out.println(uls.getUserLoginInfo().size());
    }

}

 

posted @ 2017-02-16 21:56  Realvie  阅读(5253)  评论(0编辑  收藏  举报