欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mybatis中的 mybatis-generator:generate 代码生成器的使用

程序员文章站 2024-03-19 20:52:40
...

mybatis当中 有 非常方便快捷使用的 generator,代码生成器,方便开发者使用

具体使用方法如下:

首先,我们创建一个maven项目,如下图所示:

mybatis中的 mybatis-generator:generate 代码生成器的使用


pom.xml 文件中进行如下的配置:

<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>mybatisGenerator</groupId>
  <artifactId>mybatisGeneratortest</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  
  
  
  	
  	<!-- 配置文件  -->
  	<properties>
        <java.version>1.8</java.version>
        <java.encoding>UTF-8</java.encoding>
    </properties>
  
  
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.2</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.6</version>
        </dependency>

    
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
             <version>5.1.26</version>
         </dependency>
         
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.3</version>
                <configuration>
                    <configurationFile>src/test/resources/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
            
            <!-- 
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <encoding>${java.encoding}</encoding>
                    <compilerArguments>
                        <extdirs>lib</extdirs>
                    </compilerArguments>
                </configuration>
            </plugin>
             -->
            
        </plugins>
        
        
    </build>
  
</project>

mybatis-config.xml 主配置文件如下:

<?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:3306/test"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
        
      </dataSource>
    </environment>
  </environments>
  
  
  <mappers>
  	<mapper resource="com/zwz/mapper/UserMapper.xml" />
  </mappers>
	
</configuration>


生成器配置 xml文件 generatorConfig.xml文件:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <classPathEntry location="F:\myeclipse_workspace\gupao-springmvc\gupao-generator\src\main\resources\mybatis\mysql-connector-java-5.1.8.jar"/>

    <context id="MysqlTables" targetRuntime="MyBatis3">
        <!--去除注释  -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test"
                        userId="root"
                        password="root">
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <javaModelGenerator targetPackage="com.zwz.entity" targetProject="F:\myeclipse_workspace\mybatisGeneratortest\src\main\java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="com.zwz.mapper" targetProject="F:\myeclipse_workspace\mybatisGeneratortest\src\main\java">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <javaClientGenerator type="XMLMAPPER" targetPackage="com.zwz.dao" targetProject="F:\myeclipse_workspace\mybatisGeneratortest\src\main\java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>


	<!--  想要逆向生成的表在这里进行配置   -->
		<table schema="gp" tableName="user" domainObjectName="User">
            <property name="useActualColumnNames" value="false"/>
            <!--<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>

在项目中右键,run as --> maven build ,然后在 goals当中输入 mybatis-generator:generate,于是便可以看到 在相对应配置的包目录下生成了对应的 实体类,Mapper文件,Mapper.xml文件,如下:

mybatis中的 mybatis-generator:generate 代码生成器的使用

最后一步,编写测试类进行mybatis的测试:

mybatisDemo文件如下:

package com.zwz.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.zwz.dao.UserMapper;
import com.zwz.entity.User;


public class MybatisDemo {

	//获取到sqlSession
	public static SqlSession getSqlSession() throws Exception{
		InputStream configFile = new FileInputStream(
                "F:\\myeclipse_workspace\\mybatisGeneratortest\\src\\test\\resources\\mybatis-config.xml");
		
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configFile);
        
        //加载配置文件得到SqlSessionFactory
        return sqlSessionFactory.openSession();
	}
	
	public static void main(String[] args) throws Exception {
		
		SqlSession sqlSession = getSqlSession();
		
		UserMapper um = sqlSession.getMapper(UserMapper.class);
		
		User user = um.selectByPrimaryKey("2");
		
		System.out.println(  user.getName() );
		
	}
	
}

测试后输出正确结果,是数据库当中的信息。


生成了代码之后,可以在此基础上使用  UserExample的  Criteria  进行结果的查询,查询的代码如下:

public static void main(String[] args) throws Exception {
	
		UserExample userExample = new UserExample(); 
		
		userExample.setOrderByClause("id desc"); //设置排序规则
		
		userExample.createCriteria().andAgeBetween("2", "3");	//创建 Criteria 并且设置查询规则
		
		UserMapper um = getSqlSession().getMapper( UserMapper.class ); //设置好了之后从 SqlSession 中获取到这个 UserMapper的实例对象
		
		List<User>list = um.selectByExample(userExample);	//查询实例
	
		for(User u:list){
			System.out.println( u.getName() );
		}
		
		userExample.clear();	//执行了这句clear之后代表着 userExample接下来就可以进行复用了,不受之前添加条件的影响
	
		System.out.println("--------------------------------");
		
		
		userExample.createCriteria().andIdGreaterThan("2");
		UserMapper um1 = getSqlSession().getMapper( UserMapper.class );
		
		List<User>list2 = um1.selectByExample(userExample);
	
		for(User u:list2){
			System.out.println( u.getName() );
		}
		
	}