mybatis之generator简单入门

一、generator简介

MyBatis Generator(MBG)是MyBatis MyBatis 和iBATIS的代码生成器。它将为所有版本的MyBatis以及版本2.2.0之后的iBATIS版本生成代码。它将内省数据库表(或许多表),并将生成可用于访问表的工件。这减少了设置对象和配置文件以与数据库表交互的初始麻烦。MBG寻求对简单CRUD(创建,检索,更新,删除)的大部分数据库操作产生重大影响。(一句话,generator可以自动生成代码和映射文件,但是多表查询还是需要我们去配置,即使这样也可以省很多功夫)

二、generator配置

generator官网:http://www.mybatis.org/generator/index.html

1.导包(后面跟mybatis整合,所以顺便把mybatis的包也导了)

<properties>
  	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  		<junit.version>4.12</junit.version>
  		<slf4j.version>1.7.25</slf4j.version>
  		<javax.servlet.jsp-api.version>2.3.1</javax.servlet.jsp-api.version>
		<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
  		<mysql.version>5.1.38</mysql.version>
  		<mybatis.version>3.4.6</mybatis.version>
  		<mybatis-generator-core.version>1.3.7</mybatis-generator-core.version>
  </properties>
  <dependencies>
  <!-- mybatis-generator -->
  <dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>${mybatis-generator-core.version}</version>
</dependency>
  <!-- mybatis框架 -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>${mybatis.version}</version>
</dependency>
    	<!-- mysql connector-->
	<dependency>
	    <groupId>mysql</groupId>
	    <artifactId>mysql-connector-java</artifactId>
	    <version>${mysql.version}</version>
	</dependency>
	<!--jsp、servlet支持, provide属性表示只参与测试,不加载导war包中 -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>${javax.servlet.jsp-api.version}</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${javax.servlet-api.version}</version>
			<scope>provided</scope>
		</dependency>
		<!-- log4j -->
	<dependency>
	    <groupId>org.slf4j</groupId>
	    <artifactId>slf4j-log4j12</artifactId>
	    <version>${slf4j.version}</version>
	    <scope>test</scope>
	</dependency>
  <!-- junit测试支持 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

2.generator-config.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>
  <!-- 文件id,必须配置且唯一 -->
  <context id="MyGnerator" targetRuntime="MyBatis3">
  <!-- 去除自动生成代码的注释 -->
  <commentGenerator>
  	<!-- 去除代码的注释 -->
    	<property name="suppressAllComments" value="true"/>
    <!-- 去掉代码生成时间戳 -->
    	<property name="suppressDate" value="true"/>
    </commentGenerator>
    <!--  配置数据库
  <classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" /> -->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf8"
        userId="blog"
        password="blog">
    </jdbcConnection>
<!-- java和数据库类型转换 -->
  <!--   <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver> -->
<!-- targetPackage是输出包路径 -->
    <javaModelGenerator targetPackage="com.mybatis_generator_demo.domain" targetProject="src/main/java">
    <!-- enableSubPackages是否开启子包名,即在在包名后面加上scheme名称 -->
      <property name="enableSubPackages" value="false" />
      <!-- set方法是否加.trim -->
      <property name="trimStrings" value="true" />
    </javaModelGenerator>
<!-- mapper.xml映射文件配置 -->
    <sqlMapGenerator targetPackage="com.mybatis_generator_demo.mapper"  targetProject="src/main/java">
      <property name="enableSubPackages" value="false" />
    </sqlMapGenerator>
<!-- mapper接口  -->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.mybatis_generator_demo.mapper"  targetProject="src/main/java">
      <property name="enableSubPackages" value="false" />
    </javaClientGenerator>
<!-- 配置数据库表,至少需要配置一个表名(表需要在数据库中提前创建好,generator会根据数据库中的表生成代码) -->
<table tableName="t_user"/>
<!-- <table tableName="t_country"/>
<table tableName="t_teacher"/>
<table tableName="t_city"/>
<table tableName="t_province"/>
<table tableName="t_course"/>
<table tableName="t_student"/> -->
    <!-- <table schema="DB2ADMIN" tableName="ALLTYPES" domainObjectName="Customer" >
      <property name="useActualColumnNames" value="true"/>
      <generatedKey column="ID" sqlStatement="DB2" identity="true" />
      <columnOverride column="DATE_FIELD" property="startDate" />
      <ignoreColumn column="FRED" />
      <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
    </table> -->

  </context>
</generatorConfiguration>

3.启动generator

package com.mybatis_generator_demo.geberator;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

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;

public class generator {
	public static void main(String[] args) {
		try {
			List<String> warnings = new ArrayList<String>();
			boolean overwrite = true;
			File configFile = new File("src/main/resources/generatorConfig.xml");
			ConfigurationParser cp = new ConfigurationParser(warnings);
			Configuration config = cp.parseConfiguration(configFile);
			DefaultShellCallback callback = new DefaultShellCallback(overwrite);
			MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
			myBatisGenerator.generate(null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

4.运行结果

运行前:什么代码都没有,只有一个generator启动代码
在这里插入图片描述
运行后:数据库表对应的实体类和mapper接口以及mapper.xml文件
在这里插入图片描述

三、与mybatis整合到一起

1.db.properties(需要修改为自己的数据库和用户信息)

dataSource.driver=com.mysql.jdbc.Driver
dataSource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8
dataSource.username=blog
dataSource.password=blog

2.配置文件

<?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>
<!--  引入外部配置文件-->
	<properties resource="db.properties"></properties>
	<!-- 别名设置,不设置时引用要使用全包名,设置后可以使用自定义别名,更加简洁 -->
	<typeAliases>
		<!-- 别名设置有两种,一种是一个一个设置,另外一种是设置某个包,默认别名为类名(大小写都可) -->
		<!-- 第一种设置 
	 	<typeAlias type="com.mybatis_demo.domain.User" alias="user"/>-->
	 	<!-- 第二种设置,整个包下面的类都进行别名设置,推荐第二种 -->
	 	<package name="com.mybatis_generator_demo.domain"/>
	 </typeAliases>
<!-- 环境模式:development开发模式 work工作模式 -->
  <environments default="development">
  <!-- 环境变量 -->
    <environment id="development">
    <!-- 使用jdbc的事务管理 -->
      <transactionManager type="JDBC"/>
      <!-- 使用连接池 -->
      <dataSource type="POOLED">
        <property name="driver" value="${dataSource.driver}"/>
        <property name="url" value="${dataSource.url}"/>
        <property name="username" value="${dataSource.username}"/>
        <property name="password" value="${dataSource.password}"/>
      </dataSource>
    </environment>
  </environments>
  <!-- 引入mapper映射文件 -->
  <mappers>
  <!--  1.相对路径引入-->
   <!--  <mapper resource="mapper/UserMapper.xml"/> -->
    <!-- 2.绝对路径引入 -->
    <!-- <mapper url="file:\\\D:\sts-bundle\workplace\mybatis_demo\src\main\resources\mapper\UserMapper.xml"/> -->
    <!-- 3.对应mapper接口全包名引入,需要对应的mapper.xml与接口mapper处于同一包下才可以,且xml文件名与接口名要相同,xml文件中的namespace必须是对应接口的全包名 -->
    <!-- <mapper class="com.mybatis_demo.mapper.UserMapper"/> -->
    <!-- 4.包引入,要求跟接口引入一样 -->
   <!--  <mapper resource="mapper/UserMapper2.xml"/> -->
    <package name="com.mybatis_generator_demo.mapper"/>
  </mappers>
</configuration>

3.测试代码(简单测试了几个方法,generator提供了丰富的单表操作方法,需要再研究研究)

package com.mybatis_generator_demo.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import com.mybatis_generator_demo.domain.TUser;
import com.mybatis_generator_demo.domain.TUserExample;
import com.mybatis_generator_demo.domain.TUserExample.Criteria;
import com.mybatis_generator_demo.mapper.TUserMapper;

public class TestMapper {
	//条件删除用户
	@Test
	public void test_delete() {
		 try {
			InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			SqlSessionFactory sqlSessionFactory = builder.build(in);
			SqlSession session = sqlSessionFactory.openSession();
			TUserMapper mapper = session.getMapper(TUserMapper.class);
			TUserExample example = new TUserExample();
			example.createCriteria().andUidBetween(50, 60);
			int result = mapper.deleteByExample(example);
			session.commit();
			if(result>0) System.out.println("success");
			else System.out.println("failure");
		 } catch (IOException e) {
			e.printStackTrace();
		}
	}
	//根据id集合查询用户信息
	@Test
	public void test_andUidIn() {
		 try {
			InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			SqlSessionFactory sqlSessionFactory = builder.build(in);
			SqlSession session = sqlSessionFactory.openSession();
			TUserMapper mapper = session.getMapper(TUserMapper.class);
			TUserExample example = new TUserExample();
			List<Integer> list = new ArrayList<Integer>();
			list.add(1);
			list.add(5);
			list.add(108);
			list.add(53);
			example.createCriteria().andUidIn(list);
			List<TUser> users = mapper.selectByExample(example);
			for (TUser tUser : users) {
				System.out.println(tUser);
			}
		 } catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//条件更新用户信息
	@Test
	public void test_updateByExample() {
		 try {
			InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			SqlSessionFactory sqlSessionFactory = builder.build(in);
			SqlSession session = sqlSessionFactory.openSession();
			TUserMapper mapper = session.getMapper(TUserMapper.class);
			TUserExample example = new TUserExample();
			example.createCriteria().andUnameEqualTo("测试插入");
			TUser u = new TUser();
			u.setAddress("广东");
			u.setAge(225);
			u.setUname("李飞");
			int result = mapper.updateByExampleSelective(u, example);
			if(result>0) System.out.println("success");
			else System.out.println("failure");
			session.commit();
		 } catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//多条件or查询
	@Test
	public void test_selectByExample2() {
		 try {
			InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			SqlSessionFactory sqlSessionFactory = builder.build(in);
			SqlSession session = sqlSessionFactory.openSession();
			TUserMapper mapper = session.getMapper(TUserMapper.class);
			TUserExample example = new TUserExample();
			example.createCriteria().andAgeBetween(1, 10).andAddressLike("%北京%");
			Criteria c2 = example.createCriteria().andUnameEqualTo("老王");
			example.or(c2);
			List<TUser> list = mapper.selectByExample(example);
			for (TUser tUser : list) {
				System.out.println(tUser);
			}
		 } catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	//多条件and查询
	@Test
	public void test_selectByExample() {
		 try {
			InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			SqlSessionFactory sqlSessionFactory = builder.build(in);
			SqlSession session = sqlSessionFactory.openSession();
			TUserMapper mapper = session.getMapper(TUserMapper.class);
			TUserExample example = new TUserExample();
			example.createCriteria().andAgeBetween(1, 10).andAddressLike("%北京%");
			List<TUser> list = mapper.selectByExample(example);
			for (TUser tUser : list) {
				System.out.println(tUser);
			}
		 } catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//插入用户到数据库
	@Test
	public void test_insert() {
		 try {
			InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			SqlSessionFactory sqlSessionFactory = builder.build(in);
			SqlSession session = sqlSessionFactory.openSession();
			TUserMapper mapper = session.getMapper(TUserMapper.class);
			TUser u = new TUser();
			u.setAddress("四川");
			u.setAge(22);
			u.setUname("测试插入");
			int result = mapper.insert(u);
			if(result>0) System.out.println("success");
			else System.out.println("failure");
			session.commit();
		 } catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//根据主键获取用户信息
	@Test
	public void test_selectByPrimaryKey() {
		 try {
			InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			SqlSessionFactory sqlSessionFactory = builder.build(in);
			SqlSession session = sqlSessionFactory.openSession();
			TUserMapper mapper = session.getMapper(TUserMapper.class);
			TUser TUser = mapper.selectByPrimaryKey(3);
			System.out.println(TUser);
		 } catch (IOException e) {
			e.printStackTrace();
		}
	}
}

mybatis也能方向生成代码,能方向生成实体类(po)、mapper接口和Mapper接口映射文件,能减少我们代码的工作量。详细步骤如下 1、下载mybatis生成架包工具MyBatis_Generator_1.3.1.zip,解压架包把features、plugins文件夹下的架包分别拷贝到eclipse安装目录下的features、plugins文件夹。重启eclipse就行。 解压后图片如下: Eclipse路径如图: 拷贝替换如图: 2、创建generatorConfig.xml文件,安装好mybatis 就能创建generatorConfig.xml 3、配置generatorConfig.xml配置文件,详细如下 [html] view plain copy <?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:\\rep\\mysql\\mysql-connector-java\\5.1.19\\mysql-connector-java-5.1.19.jar" /> --> <classPathEntry location="D:\\repo\\com\\oracle\\ojdbc14\\10.2.0.1.0\\ojdbc14-10.2.0.1.0.jar" /> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressAllComments" value="true" /> <property name="suppressDate" value="true" /> </commentGenerator> <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@xxx.xxx.xxx.xxx:1521:orcl4" userId="xxx" password="xxxx" /> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer true,把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal --> </javaTypeResolver> <javaModelGenerator targetPackage="com.pcmall.domain.sale.order" targetProject="pos-service/src/main/java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <sqlMapGenerator targetPackage="mybatis.mapper.sale.order" targetProject="pos-service/src/main/resources"> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <javaClientGenerator targetPackage="com.pcmall.dao.sale.order" targetProject="pos-service/src/main/java" type="XMLMAPPER"> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <table tableName="hs_zxzflx" enableSelectByExample="false" enableDeleteByExample="false" enableCountByExample="false" selectByExampleQueryId="true" enableUpdateByExample="false"> <!-- <generatedKey column="ID" sqlStatement="oracle" identity="true" /> --> </table> </context> </generatorConfiguration> 4、右击generatorConfig.xml 点击Generate MyBatis/iBATIS Artifacts 生成对应接口、接口映射文件、实体类 5、查看结果
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值