首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring MVC 與 MyBatis 整合完整配置指南

     編輯:Java 綜合教學

Spring MVC 與 MyBatis 整合完整配置指南

本文詳細記錄 Spring MVC + MyBatis 整合全過程,涵蓋逆向工程代碼生成、多模塊配置文件拆分、事務管理、攔截器、文件上傳、RESTful 風格等企業級開發核心功能。

一、MyBatis Generator 逆向工程配置

<generatorConfiguration>
  <context id="testTables" targetRuntime="MyBatis3">
    <commentGenerator>
      <property name="suppressAllComments" value="true"/>
    </commentGenerator>
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://localhost:3307/mybatis"
        userId="root" password="jalja"/>
    <javaTypeResolver>
      <property name="forceBigDecimals" value="false"/>
    </javaTypeResolver>
    <javaModelGenerator targetPackage="com.jalja.springmvc_mybatis.model.pojo"
        targetProject=".\src">
      <property name="enableSubPackages" value="false"/>
      <property name="trimStrings" value="true"/>
    </javaModelGenerator>
    <sqlMapGenerator targetPackage="com.jalja.springmvc_mybatis.mapper"
        targetProject=".\src">
      <property name="enableSubPackages" value="false"/>
    </sqlMapGenerator>
    <javaClientGenerator type="XMLMAPPER"
        targetPackage="com.jalja.springmvc_mybatis.mapper"
        targetProject=".\src">
      <property name="enableSubPackages" value="false"/>
    </javaClientGenerator>
    <table tableName="items"/>
    <table tableName="orders"/>
    <table tableName="orderdetail"/>
    <table tableName="user"/>
  </context>
</generatorConfiguration>

二、核心配置文件架構

config/
├── mybatis/
│   └── applicationContext-mybatis.xml   # MyBatis 核心配置
├── spring/
│   ├── applicationContext-dao.xml       # 數據源、事務、Mapper 掃描
│   ├── applicationContext-service.xml   # Service Bean 定義
│   └── springmvc.xml                    # Spring MVC 配置
├── jdbc.properties                      # 數據庫連接參數
└── log4j.properties                     # 日誌配置

三、關鍵配置解析

1. web.xml — 容器啟動入口

  • ContextLoaderListener 載入 Spring 容器
  • DispatcherServlet 處理 *.do 請求
  • CharacterEncodingFilter 解決 POST 亂碼
  • Log4jConfigListener 初始化日誌

2. applicationContext-dao.xml — 數據層核心

<!-- DBCP 連接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
  <property name="driverClassName" value="${jdbc_driverClassName}"/>
  <property name="url" value="${jdbc_url}"/>
  <property name="username" value="${jdbc_username}"/>
  <property name="password" value="${jdbc_password}"/>
  <property name="maxActive" value="20"/>
  <property name="initialSize" value="1"/>
</bean>

<!-- SqlSessionFactory 整合 MyBatis -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource"/>
  <property name="configLocation" value="classpath:mybatis/applicationContext-mybatis.xml"/>
</bean>

<!-- Mapper 掃描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="com.jalja.springmvc_mybatis.mapper"/>
  <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>

<!-- 聲明式事務 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
  <tx:attributes>
    <tx:method name="update*" propagation="REQUIRED"/>
    <tx:method name="save*" propagation="REQUIRED"/>
    <tx:method name="delete*" propagation="REQUIRED"/>
    <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
    <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
  </tx:attributes>
</tx:advice>
<aop:config>
  <aop:advisor advice-ref="txAdvice"
      pointcut="execution(* com.jalja.springmvc_mybatis.service.impl.*.*(..))"/>
</aop:config>

3. springmvc.xml — Web 層配置

  • <mvc:annotation-driven/> 啟用註解驅動、JSON 轉換
  • <context:component-scan> 掃描 Controller
  • 自定義 ConversionService 處理日期類型綁定
  • 全局異常解析器 CustomExceptionResolver
  • 文件上傳 CommonsMultipartResolver (5MB 限制)
  • 攔截器鏈 LoginInterceptor 保護全部路徑
  • InternalResourceViewResolver 配置 JSP 視圖解析

四、Controller 實戰範例

@Controller
@RequestMapping("/items")
public class ItemsController {
    @Autowired ItemsService itemsService;
    
    @RequestMapping("/findItemsList")
    public String findItemsList(Model model) throws Exception {
        List list = itemsService.findItemsList(null);
        model.addAttribute("itemsList", list);
        return "itemsList";
    }
    
    @RequestMapping(value="/editItems", method={RequestMethod.GET, RequestMethod.POST})
    public String editItems(Model model, 
        @RequestParam(value="id", required=true, defaultValue="0") Integer id) throws Exception {
        ItemsCustom item = itemsService.findItemsById(id);
        if (item == null) throw new CustomException("商品不存在");
        model.addAttribute("itemsCustom", item);
        return "editItems";
    }
    
    @RequestMapping("/updateItems")
    public String updateItems(Integer id, ItemsCustom item, 
        MultipartFile itemsPic) throws Exception {
        if (itemsPic != null && !itemsPic.isEmpty()) {
            String origName = itemsPic.getOriginalFilename();
            String newName = UUID.randomUUID() + origName.substring(origName.lastIndexOf('.'));
            itemsPic.transferTo(new File("E:/develop/upload/images/" + newName));
            item.setPic(newName);
        }
        itemsService.updateItemsById(id, item);
        return "redirect:findItemsList.do";
    }
    
    @ResponseBody
    @RequestMapping("/jsonRequest")
    public ItemsCustom jsonRequest(@RequestBody ItemsCustom item) {
        return item; // 自動轉 JSON
    }
    
    @ResponseBody
    @RequestMapping("/restFulRequest/{id}")
    public ItemsCustom restFulRequest(@PathVariable("id") Integer id) throws Exception {
        return itemsService.findItemsById(id);
    }
}

五、整合要點總結

  1. 分層解耦:DAO/Service/Controller 清晰分離
  2. 配置模塊化:按關注點拆分 XML,便於維護
  3. 事務邊界:在 Service 實現類切面織入,遵循命名約定
  4. 類型轉換:擴展 ConversionService 解決日期綁定
  5. 異常統一:HandlerExceptionResolver 實現全局錯誤處理
  6. REST 支援:@PathVariable + @ResponseBody 輕鬆實現
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved