StringMVC和myBatis框架整合

来源:互联网 发布:《大数据时代》好句 编辑:程序博客网 时间:2024/05/12 14:14

使用步骤

1.导入jar包(两者的并集)

2.配置web.xml:

主要有两项,分别是对springmvc用到的DispatcherServlet的配置 和  Spring框架中的监听器(与context-param配合,以使applicationContext文件能被读取)

3.在WEB-INF下建立aaa-servlet.xml文件,为控制器和处理器建立联系

4.在源代码文件包etc中建立applicationContext.xml

配置数据源,事务管理器,MyBatis(包含数据源与别名),以及mapper文件位置的扫描

5.测试:

包结构类似于ssh 框架,有entity,mapper(相当于dao,含有xml与接口两类文件),service,  web

在service中需要注入mapper,

[html] view plain copy
  1. @Service  
  2. @Transactional  
  3. public class UserService {  
  4.   
  5.     @Resource  
  6.     private UserMapper userMapper;  
  7.       
  8.     public User findById(long id) {  
  9.         return userMapper.findById(id);  
  10.     }  
  11.       
  12.     public void save(User user) {  
  13.         userMapper.save(user);  
  14.     }  
  15. }  


在web的Controller类中需要注入service


[html] view plain copy
  1. @Controller  
  2. public class UserController {  
  3.   
  4.     @Resource  
  5.     private UserService userService;  
  6.       
  7.     @RequestMapping("/user")  
  8.     public void find(){  
  9.         User user = userService.findById(1);  
  10.           
  11.         System.out.println(user.getUsername());  
  12.     }  
  13. }  
部署,启动服务后,在浏览器中输入xxx/user,会看到控制台打印用户名