Spring-mybtis整合过程详解

Spring-mybtis整合过程详解,第1张

Spring-mybtis整合过程详解

一、创建完整包 下载地址:01MyBatis基础代码.zip-Web开发文档类资源-CSDN下载

二、开始整合

1、方式1

step1:导入相关坐标



            mysql
            mysql-connector-java
            8.0.27
        
        
            org.mybatis
            mybatis
            3.5.7
        
        
            log4j
            log4j
            1.2.17
        
        
        
            org.springframework
            spring-context
            5.3.13
        
        
        
            org.springframework
            spring-jdbc
            5.3.13
        
        
        
            org.mybatis
            mybatis-spring
            2.0.6
        
        
        
            com.alibaba
            druid
            1.2.8
        
    

step2:修改daoImpl中代码

修改serviceImpl中代码

step3:创建bean.xml



    
    
    
    
    
    

    
    
        

    
        
    
    
         
    

 step4:编写测试代码

import com.woniuxy.model.Category;
import com.woniuxy.service.CategoryService;
import com.woniuxy.service.impl.CategoryServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class TestCategoryService {
    private static CategoryService categoryService = new CategoryServiceImpl();

    public static void main(String[] args) {
        testFindAllCategories();
    }

    private static void testFindAllCategories() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:bean.xml");
        CategoryService categoryService = (CategoryServiceImpl)ac.getBean("categoryService");
        List categories = categoryService.findAllCategories();
        for(Category category : categories){
            System.out.println(category.getName());
        }
    }
}

step5:测试结果

 方式2:使用SqlSessionTemplate

基于以上代码

step1:修改daoImpl代码 注意:不需要提交commit()和close()的事务提交,因为spring容器已经帮你做了

 是step2:修改bean.xml

step3:测试代码和上面一致,结果如下

 

 3、方式3 基于以上代码修改

step1:修改daoImpl

 step2:修改bean.xml

 step3:测试代码一样,测试结果

 4、方式4 可利用MapperFactoryBean创建Mapper

基于以上代码

step1:修改daoImpl

step2:修改bean.xml

 step3:测试代码和测试结果同上

4、最终解决方案 基于以上代码

step1:

step2:修改bean.xml 

 step3:删除dao整个包

 step4:测试代码同上和测试结果

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5673151.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-17

发表评论

登录后才能评论

评论列表(0条)

    保存