利用MyBatis Generator自动创建代码
结合Spring使用Mybatis Generator生成的代码http://www.360doc.com/content/11/0131/12/834950_90117757.shtml
原文地址:http://maimode.iteye.com/blog/1539983
如果你使用过hibernate的eclipse插件自动创建DAO文件,那么就容易理解下面介绍的内容;如果你还没有用过hibernate也无妨。下面介绍使用mybatis 3的eclipse插件自动生成相关文件以及如何使用这些文件。
eclipse插件安装地址:http://mybatis.googlecode.com/svn/sub-projects/generator/trunk/eclipse/UpdateSite/
附件有link安装包,link安装方式参考http://maimode.iteye.com/admin/blogs/1164524
MyBatis Generator详细介绍参见:http://code.google.com/p/mybatis/wiki/Generator
安装插件的过程就不说了,安装完后,eclipse中File-》new-》other中会发现多了mybatis选项说明插件安装成功。

如何使用插件
在任意项目中利用上图中的向导创建generatorConfig.xml文件(名称可修改)然后修改文件内容,主要是设置连接数据的相关参数:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > <generatorConfiguration > <context id="context1" > <jdbcConnection driverconnectionURL="jdbc:oracle:thin:@192.168.2.21:1521:ORCL" userId="atfm" password="atfm" /> <javaModelGenerator targetPackage="com.topsci.atfm.persistence.mybatis.model" targetProject="ATFM" /> <sqlMapGenerator targetPackage="com.topsci.atfm.persistence.mybatis.mapper" targetProject="ATFM" ></sqlMapGenerator> <javaClientGenerator targetPackage="com.topsci.atfm.persistence.mybatis.client" targetProject="ATFM" type="XMLMAPPER" /> <table schema="" tableName="ATFM_ROUTE_CTRL" ></table> <table tableName="SYN_TRACK_EST" domainObjectName="AtfmTrack"></table> </context> </generatorConfiguration>

public List<TrackBean> selectTrackOnRoute(String routeName) { List<TrackBean> rt = null; SqlSession session = null; try { session = sqlSessionFactory.openSession(); AtfmTrackMapper mapper = session.getMapper(AtfmTrackMapper.class); // 构造查询条件 AtfmTrackExample example = new AtfmTrackExample(); example.createCriteria() .andRouteIs(routeName); // 查询 List<AtfmTrack> list = mapper.selectByExample(example); // 包装成TrackBean rt = this.toTrackBean(list); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); } finally { if (session != null) session.close(); } return rt; } public Criteria andRouteIs(String routeName){ StringBuffer sb = new StringBuffer("point_name in " + "(select p.point from route_point p where p.route = '" + routeName + "') " + "AND FLIGHT_NO IN " + "(select D.FLIGHT_NO from syn_aftn_dynamic_recent d " + "where d.route like '%" + routeName + "%')"); addCriterion(sb.toString()); return this; }