网站首页
Java
站长
开源
框架
理论
JS
Linux
DB
服务器
NET
生活
软件
PHP
其他
您的位置:首页 > 开源 > MyBatis Generator自动生成MyBatis代码
MyBatis Generator自动生成MyBatis代码
2015-12-8    13085    0

首先是安装插件,我这里用的是MyBatis_Generator_1.3.1。

获取相应数据库的驱动Jar包,这里是MySQL。

编写要自动生成的数据库表


CREATE TABLE `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `birthday` datetime DEFAULT NULL,
  `money` float DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


编写对应数据库的配置文件,一般一个数据库对应一个配置文件即可。


<?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:\JAD\mysql-connector-java-5.1.26.jar" />
  <context id="context1" >
    <commentGenerator>
		<property name="suppressAllComments" value="true" />
	</commentGenerator>	 	
	<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" 
	userId="root" password="root" />
	
	<javaModelGenerator targetPackage="com.codelog.entity" targetProject="mybatis" />		
	<sqlMapGenerator targetPackage="com.codelog.dao" targetProject="mybatis" />
	<javaClientGenerator targetPackage="com.codelog.dao" targetProject="mybatis" type="XMLMAPPER" />
	
	<table schema="" tableName="test" enableCountByExample="true" enableDeleteByExample="true" 
	selectByExampleQueryId = "true" enableDeleteByPrimaryKey = "true">
	</table>
  </context>
</generatorConfiguration>

在Eclipse右键,生成相应的代码


利用MyBatis Generator自动创建代码


实用示例


package com.codelog.test;
import java.util.Date;
import java.util.List;
import com.codelog.dao.TestMapper;
import com.codelog.entity.Test;
import com.codelog.entity.TestExample;
import com.codelog.entity.TestExample.Criteria;
public class TestCase {
	private static TestMapper mp = null;
	public static void main(String[] args) {
		Test record = new Test();
		record.setName("java小强");
		record.setBirthday(new Date());
		record.setMoney(new Float("12.12"));
		mp.insert(record); // 新增
		
		mp.deleteByPrimaryKey(1); // 根据ID删除
		
		TestExample example = new TestExample();
		Criteria criteria = example.createCriteria();
		criteria.andBirthdayLessThan(new Date()); // 加一个参数		
		mp.deleteByExample(example); // 根据条件删除
		
		record = mp.selectByPrimaryKey(1); // 根据ID查询
		record.setBirthday(new Date());
		mp.updateByPrimaryKeySelective(record); // 根据ID更新
		
		mp.updateByExample(record, example); // 根据条件更新,注意record为null的列不操作
		
		example.setOrderByClause("id desc"); // 增加排序
		List<Test> list = mp.selectByExample(example);
		System.out.println(list.size());
	}
}

注意,查询没有分页参数,这里只是简单示例,后续再说分页的问题。

最后工程目录


利用MyBatis Generator自动创建代码



插件文件下载,联系站长。注意在工程增加mybatis-3.2.8.jar这个Jar包。

上一篇: Eclipse上配置tomcat6.0服务
下一篇: 再说TbViewer,服务器上那些恶意软件
发表评论:
您的网名:
个人主页:
编辑内容: