本文詳細記錄 Spring MVC + MyBatis 整合全過程,涵蓋逆向工程代碼生成、多模塊配置文件拆分、事務管理、攔截器、文件上傳、RESTful 風格等企業級開發核心功能。
<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 # 日誌配置
ContextLoaderListener 載入 Spring 容器DispatcherServlet 處理 *.do 請求CharacterEncodingFilter 解決 POST 亂碼Log4jConfigListener 初始化日誌<!-- 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>
<mvc:annotation-driven/> 啟用註解驅動、JSON 轉換<context:component-scan> 掃描 ControllerConversionService 處理日期類型綁定CustomExceptionResolverCommonsMultipartResolver (5MB 限制)LoginInterceptor 保護全部路徑InternalResourceViewResolver 配置 JSP 視圖解析@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);
}
}
ConversionService 解決日期綁定HandlerExceptionResolver 實現全局錯誤處理@PathVariable + @ResponseBody 輕鬆實現