打开eclipse,点击Help>Software Update
选择 "Available Software" 标签,点击 "Add Site" 按钮
输入以下信息:
Location:http://mybatis.googlecode.com/svn/sub-projects/generator/trunk/eclipse/UpdateSite/
点击ok,自动进入 "mybatis generator Feature"
点击“install”按钮进行安装。。。。mybatis generator 插件安装完成
<?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 > <classPathEntry location="D:/ojdbc5-11.2.0.2.0.jar" /> <context id="context1" > <!-- 配置连接数据信息 --> <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@192.168.1.233:1521:orcl" userId="cmss" password="cmss" /> <!-- 配置自动生成的Model的保存路径与其它参数 --> <javaModelGenerator targetPackage="com.entity.main" targetProject="MyIbatisGeneratorForPage\src\main\java" /> <!-- 配置自动生成的Mappper.xml映射的保存路径与其它参数 --> <sqlMapGenerator targetPackage="config.myibatis.xml" targetProject="MyIbatisGeneratorForPage\src\main\resources" /> <!-- 配置自动生成的Mappper.java接口的保存路径与其它参数 --> <javaClientGenerator targetPackage="com.dao" targetProject="MyIbatisGeneratorForPage\src\main\java" type="XMLMAPPER" /> <!-- <table schema="" tableName="T_SYS_USER"></table> <table schema="" tableName="T_SYS_ROLE"></table> <table schema="" tableName="T_SYS_ORG"></table> <table schema="" tableName="T_SYS_ROLE_RES"></table> <table schema="" tableName="T_SYS_RESOURCE"></table> <table schema="" tableName="T_SYS_USER_ROLE"></table> --> <!-- 生成表对应的操作与实体对象 --> <table schema="" tableName="T_CORE_ORG_HIS"></table> </context> </generatorConfiguration>
1.创建一个Maven项目:File——New Project——Maven
2.在pom文件中,添加Myibatis-Generator插件,IDE会自动帮我们下载插件
(如果没反应,可以点开右侧Maven Project选项卡刷新以下)
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>Mybatis_Generator</groupId> <artifactId>Mybatis_Generator</artifactId> <version>1.0-SNAPSHOT</version> <build> <finalName>mybatis_generator</finalName> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.0</version> </plugin> </plugins> </build> </project>
3.在src/main/resource目录下创建generatorConfig.xml文件
(官方配置以及说明:http://go.rritw.com/mybatis.github.io/generator/configreference/xmlconfig.html)
<?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> <!--数据库驱动jar --> <classPathEntry location="E:\mysql-connector-java-5.1.7-bin.jar" /> <context id="DB2Tables" targetRuntime="Ibatis2Java5"> <!--去除注释 (true好像不起作用) --> <commentGenerator> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--数据库连接 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/news" userId="root" password=""> </jdbcConnection> <!--默认false Java type resolver will always use java.math.BigDecimal if the database column is of type DECIMAL or NUMERIC. --> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!--生成实体类 指定包名 以及生成的地址 (可以自定义地址,但是路径不存在不会自动创建 使用Maven生成在target目录下,会自动创建) --> <javaModelGenerator targetPackage="com.qianyan.model" targetProject="MAVEN"> <property name="enableSubPackages" value="false" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!--生成SQLMAP文件 --> <sqlMapGenerator targetPackage="com.qianyan.persistence.ibatis" targetProject="MAVEN"> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!--生成Dao文件 可以配置 type="XMLMAPPER"生成xml的dao实现 context id="DB2Tables" targetRuntime="MyBatis3" --> <javaClientGenerator type="SPRING" targetPackage="com.qianyan.persistence.dao" targetProject="MAVEN"> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!--对应数据库表 mysql可以加入主键自增 字段命名 忽略某字段等--> <table tableName="USER" domainObjectName="User" > </table> </context> </generatorConfiguration>4.点击Maven Project——项目——Plugins——mybatis generator——Run Maven build
5.可以根据自己项目的配置,把生成的代码拷贝到自己的项目中去
mybatis设计比较巧妙,Dao层就不用说了,这里主要介绍下实体类User和UserExample
User类就是普通的实体类,定义了数据库对应的字段,以及set/get方法
Example类是干嘛的呢?用其它项目中的几个例子还说明一下吧
1.比如在一个项目 我们要删除某个小组下某个用户的信息
public int deleteUserApplyInfo(long user_id,long team_id){ StudyTeamUserApplyInfoExample ue = new StudyTeamUserApplyInfoExample(); ue.createCriteria() .andUserIdEqualTo(new BigDecimal(user_id)) .andTeamIdEqualTo(new BigDecimal(team_id)); return studyTeamUserApplyInfoDAO.deleteByExample(ue); }
public int updateStudyTeamInfo(StudyTeamInfo st){ StudyTeamInfoExample ste = new StudyTeamInfoExample(); ste.createCriteria().andTeamIdEqualTo(st.getTeamId()); return studyTeamInfoDAO.updateByExampleSelective(st,ste); }3.(1)模糊查询并且排序 (2)大于等于某个分数 并且小于某个分数的查询
public List<StudyTeamInfo> getStudyTeamInfoByName(String team_name){ StudyTeamInfoExample se = new StudyTeamInfoExample(); se.createCriteria().andTeamNameLike("%"+team_name+"%").andEnableEqualTo((short)1); se.setOrderByClause("team_score desc"); List<StudyTeamInfo> ls = studyTeamInfoDAO.selectByExample(se); if(ls!=null&&ls.size()>0){ return ls; } return null; }
Example中提供了Critertia,一种面向对象的查询方式,并且根据实体类中字段的属性,生成不同的操作。
当然你也可以根据实际需要直接使用实体类进行增删改查。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost/test" /> <property name="username" value="test" /> <property name="password" value="test" /> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/com/xxx/mybatis/UsersMapper.xml"/> </mappers> </configuration>
Reader reader = Resources.getResourceAsReader("config/MapperConfig.xml"); SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader); SqlSession sqlSession = sqlMapper.openSession(); UsersExample example = new UsersExample(); example.createCriteria().andPasswordIsNotNull(); try { UsersMapper mapper = sqlSession.getMapper(UsersMapper.class); List<Users> users = mapper.selectByExample(example); for (Users u : users) System.out.println(u.getUsername() + " -- " + u.getPassword()); } finally { sqlSession.close(); }
import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.internal.DefaultShellCallback; ... List<String> warnings = new ArrayList<String>(); final boolean overwrite = true; File configFile = new File("src/main/resources/config/generatorConfig.xml"); //System.out.println("config fiel is in : " + configFile.getAbsoluteFile()); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration configuration = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator mybatisGenerator = new MyBatisGenerator(configuration, callback, warnings); mybatisGenerator.generate(null);
<?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> <!-- 引入配置文件 --> <properties resource="init.properties"/> <!-- 指定数据连接驱动jar地址 --> <classPathEntry location="${classPath}" /> <!-- 一个数据库一个context --> <context id="infoGuardian"> <!-- 注释 --> <commentGenerator > <property name="suppressAllComments" value="false"/><!-- 是否取消注释 --> <property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳--> </commentGenerator> <!-- jdbc连接 --> <jdbcConnection driverClass="${jdbc_driver}" connectionURL="${jdbc_url}" userId="${jdbc_user}" password="${jdbc_password}" /> <!-- 类型转换 --> <!-- false:JDBC DECIMAL、NUMERIC类型解析为Integer,默认方式 --> <!-- true: JDBC DECIMAL、NUMERIC类型解析为java.math.BigDecimal --> <javaTypeResolver> <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) --> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 生成实体类地址 --> <javaModelGenerator targetPackage="com.oop.eksp.user.model" targetProject="${project}" > <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --> <property name="enableSubPackages" value="false"/> <!-- 是否针对string类型的字段在set的时候进行trim调用 --> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 生成mapxml文件 --> <sqlMapGenerator targetPackage="com.oop.eksp.user.data" targetProject="${project}" > <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!-- 生成mapxml对应client,也就是接口dao --> <javaClientGenerator targetPackage="com.oop.eksp.user.data" targetProject="${project}" type="XMLMAPPER" > <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!-- 配置表信息 --> <table schema="${jdbc_user}" tableName="s_user" domainObjectName="UserEntity" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> <!-- schema即为数据库名 tableName为对应的数据库表 domainObjectName是要生成的实体类 enable*ByExample 是否生成 example类 --> <!-- 忽略列,不生成bean 字段 --> <ignoreColumn column="FRED" /> <!-- 指定列的java数据类型 --> <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> </table> </context> </generatorConfiguration>
#Mybatis Generator configuration project = EKSP classPath=E:/workplace/EKSP/WebContent/WEB-INF/lib/ojdbc14.jar jdbc_driver = oracle.jdbc.driver.OracleDriver jdbc_url=jdbc:oracle:thin:@127.0.0.1:1521:orcl jdbc_user=INFOGUARDIAN jdbc_password=info_idap132