MyBatis-Spring整合之方式3
Posted 方寸间
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis-Spring整合之方式3相关的知识,希望对你有一定的参考价值。
通过注解整合
1.在UserDao同级目录下新建接口UserMapper,内容如下:
public interface UserMapper {
@Select("select * from user")
public List<User> selectUser();
}
2.新建service包,改写UserDao和其实现类为UserService类和其实现类,如下:
public interface UserService {
public List<User> selectUser();
}
public class UserServiceImp implements UserService {
private UserMapper userMapper;
@Override
public List<User> selectUser() {
return userMapper.selectUser();
}
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
}
3.beans.xml新增bean标签、修改原UserDao标签,如下:
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.lxy.dao.UserMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<bean id="userService" class="com.lxy.service.imp.UserServiceImp">
<property name="userMapper" ref="userMapper"/>
</bean>
4.修改test为新的类型,如下:
public class test {
public static void main(String[] args) throws IOException {
ApplicationContext context=new ClassPathXmlApplicationContext("Beans.xml");
UserService userService= (UserService) context.getBean("userService");
System.out.println(userService.selectUser().size());
}
}
以上是关于MyBatis-Spring整合之方式3的主要内容,如果未能解决你的问题,请参考以下文章