MyBatis 為 Apache 開源項目 iBatis 遷移至 Google Code 後改名而來。本文示範 SpringMVC + MyBatis 整合全流程,包含逆向工程生成基礎代碼、分層配置、Controller 實現等。
透過 generatorConfig.xml 指定資料庫連線、目標套件、資料表等,自動生成 POJO、Mapper XML、Mapper Interface:
<generatorConfiguration>
<context id="testTables" targetRuntime="MyBatis3">
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3307/mybatis"
userId="root" password="jalja"/>
<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"/>
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.jalja.springmvc_mybatis.mapper"
targetProject=".\src"/>
<table tableName="items"/>
<table tableName="orders"/>
<table tableName="orderdetail"/>
<table tableName="user"/>
</context>
</generatorConfiguration>
ContextLoaderListener 載入 Spring 容器DispatcherServlet 作為前端控制器,映射 *.dosettings:開啟延遲載入、二級快取typeAliases:掃描 POJO、VO 套件自動註冊別名mappers 可省略,改由 MapperScannerConfigurer 掃描BasicDataSource(DBCP 連線池)SqlSessionFactoryBean 整合 MyBatisMapperScannerConfigurer 掃描 Mapper 介面生成代理DataSourceTransactionManager + AOP 切點註冊 Service 實現 Bean,如 ItemsServiceImpl。
<mvc:annotation-driven/> 啟用註解驅動<context:component-scan> 掃描 Controller@Controller
@RequestMapping("/items")
public class ItemsController {
@Autowired ItemsService itemsService;
@RequestMapping("/findItemsList")
public String findItemsList(Model model) throws Exception {
List<ItemsCustom> itemsList = itemsService.findItemsList(null);
model.addAttribute("itemsList", itemsList);
return "itemsList";
}
@RequestMapping("/editItems")
public String editItems(Model model, @RequestParam(value="id", required=true) Integer itemsId) throws Exception {
ItemsCustom itemsCustom = itemsService.findItemsById(itemsId);
if (itemsCustom == null) throw new CustomException("商品不存在");
model.addAttribute("itemsCustom", itemsCustom);
return "editItems";
}
@RequestMapping("/updateItems")
public String editItemsSubmit(Integer id, ItemsCustom itemsCustom, MultipartFile itemsPic) throws Exception {
// 檔案上傳處理、UUID 重命名、儲存路徑、更新資料庫
return "redirect:findItemsList.do";
}
@RequestMapping("/jsonRequest")
@ResponseBody public ItemsCustom jsonRequest(@RequestBody ItemsCustom itemsCustom) { ... }
@RequestMapping("/restFulRequest/{id}")
@ResponseBody public ItemsCustom restFulRequest(@PathVariable("id") Integer id) { ... }
}
@PathVariable、@RequestBody、@ResponseBody 打造現代化 API。CommonsMultipartResolver + UUID 防重名。