Spring整合MyBatis和MyBatis逆向工程


Spring整合MyBatis和MyBatis逆向工程


一、整合思路和准备

1.  集成思路

       需要spring来管理数据源信息。

        需要spring通过单例方式管理SqlSessionFactory。

        使用SqlSessionFactory创建SqlSession。(spring和mybatis整合自动完成)

        持久层的mapper都需要由spring进行管理,spring和mybatis整合生成mapper代理对象

 2.  集成步骤

        ①jar包集成;

        ②配置文件集成(数据源);

        ③SqlSessionFactory集成;

        ④Mapper接口集成;

3.  搭建工程

新建java项目

            


导入jar包



数据库

原型文件:db.properties和log4j.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root

jdbc.password=root

# Global logging configuration
#\u5728\u5f00\u53d1\u73af\u5883\u4e0b\u65e5\u5fd7\u7ea7\u522b\u8981\u8bbe\u7f6e\u6210DEBUG\uff0c\u751f\u4ea7\u73af\u5883\u8bbe\u7f6e\u6210info\u6216error
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

二、原始Dao整合

1.  PO类

        

public class User implements Serializable {

   //属性名和数据库表的字段对应
   private int id;
   private String username;// 用户姓名
   private String sex;// 性别
   private Date birthday;// 生日
   private String address;// 地址

   //用户创建的订单列表
   private List<Orders> ordersList;
public class Orders {
   private Integer id;

   private Integer userId;

   private String number;

   private Date createtime;

   private String note;

   //用户信息
   private User user;

2.  DAO类


public interface UserDao {
   //根据id查询用户信息
   public User findUserById(int id) throws Exception;
}
/**
 * UserDaoImpl继承SqlSessionDaoSupport
 * 自动方法结束就关闭资源了,不需要再close关闭资源了
 * @author DreamWF
 *
 */
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {

   @Override
   public User findUserById(int id) throws Exception {
      //继承SqlSessionDaoSupport,通过this.getSqlSession()得到sqlSessoin
      SqlSession sqlSession = this.getSqlSession();

      User user = sqlSession.selectOne("test.findUserById", id);

      return user;

   }
}

3.  Mapper映射文件:user.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离 
注意:使用mapper代理方法开发,namespace有特殊重要的作用
-->
<mapper namespace="test">

    <!-- 在 映射文件中配置很多sql语句 -->
    <!-- 需求:通过id查询用户表的记录 -->
    <!-- 通过 select执行数据库查询
    id:标识 映射文件中的 sql
    将sql语句封装到mappedStatement对象中,所以将id称为statement的id
    parameterType:指定输入 参数的类型,这里指定int型 
    #{}表示一个占位符号
    #{id}:其中的id表示接收输入 的参数,参数名称就是id,如果输入 参数是简单类型,#{}中的参数名可以任意,可以value或其它名称
    
    resultType:指定sql输出结果 的所映射的java对象类型,select指定resultType表示将单条记录映射成的java对象。
     -->
    <select id="findUserById" parameterType="int" resultType="com.cjw.ssm.po.User">
        SELECT * FROM USER WHERE id=#{value}
    </select>

</mapper>

4.  Mybatis的SqlMapConfig.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>
    <!-- 别名定义 -->
    <typeAliases>
        <!-- 批量别名定义 
        指定包名,mybatis自动扫描包中的po类,自动定义别名,别名就是类名(首字母大写或小写都可以)
        -->
        <package name="com.cjw.ssm.po"/>
    </typeAliases>

    <!-- 加载 映射文件 -->
    <mappers>
        <mapper resource="sqlMap/User.xml"/>
        <!-- 批量加载mapper
        指定mapper接口的包名,mybatis自动扫描包下边所有mapper接口进行加载
        遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录 中
        上边规范的前提是:使用的是mapper代理方法
        
        和spring整合后,使用mapper扫描器,这里不需要配置了
         -->
        <!-- <package name="com.cjw.ssm.mapper"/> -->
    </mappers>
</configuration>

5.  Spring的applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" 
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                http://www.springframework.org/schema/mvc
                http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context-3.2.xsd
                http://www.springframework.org/schema/aop
                http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
                http://www.springframework.org/schema/tx
                http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />
    <!-- 数据源,使用dbcp -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>

    <!-- 配置SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 加载mybatis的配置文件 -->
        <property name="configLocation" value="mybatis/SqlMapConfig.xml"></property>
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 原始DAO接口 -->
    <bean id="userDao" class="com.cjw.ssm.dao.UserDaoImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>

</beans>

6.  测试代码

public class UserDaoImplTest {

   private ApplicationContext applicationContext;

   //SetUp这个方法得到Spring容器
   @Before
   public void setUp() throws Exception {
      applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
   }

   @Test
   public void testFindUserById() throws Exception {

      UserDao userDao=(UserDao) applicationContext.getBean("userDao");
      //调用userDao的方法
      User user=userDao.findUserById(1);
      System.out.println(user);

   }
}

三、Mapper整合

编写PO类、采用Mapper代理就不用写DAO了,MyBatis的配置文件不用管

1.  Mapper类、Mapper配置文件UserMapper.xml

public interface UserMapper {
   
   //根据id查询用户信息
   public User findUserById(int id) throws Exception;
}

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离 
注意:使用mapper代理方法开发,namespace有特殊重要的作用,namespace等于mapper接口地址
-->
<mapper namespace="com.cjw.mapper.UserMapper">

    <select id="findUserById" parameterType="int" resultType="user">
        SELECT * FROM USER WHERE id=#{value}
    </select>

</mapper>

2.  SqlMapConfig.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>

    <!-- 别名定义 -->
    <typeAliases>


        <!-- 批量别名定义 
        指定包名,mybatis自动扫描包中的po类,自动定义别名,别名就是类名(首字母大写或小写都可以)
        -->
        <package name="com.cjw.ssm.po"/>

    </typeAliases>

    <!-- 加载 映射文件 -->
    <mappers>
        <!-- 批量加载mapper
        指定mapper接口的包名,mybatis自动扫描包下边所有mapper接口进行加载
        遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录 中
        上边规范的前提是:使用的是mapper代理方法
        
        和spring整合后,使用mapper扫描器,这里不需要配置了
         -->
        <!-- <package name="com.cjw.ssm.mapper"/>  -->

    </mappers>

</configuration>

3.  applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
      http://www.springframework.org/schema/mvc 
      http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-3.2.xsd 
      http://www.springframework.org/schema/aop 
      http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
      http://www.springframework.org/schema/tx 
      http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />
    <!-- 数据源,使用dbcp -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>

    <!-- 配置SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 加载mybatis的配置文件 -->
        <property name="configLocation" value="mybatis/SqlMapConfig.xml"></property>
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- Mapper批量扫描:从Mapper的包中扫描出Mapper接口,自动创建代理对象并且在Spring容器中注册
            遵循一些规范:需要将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录 中
            自动扫描出来的mapper的bean的id为mapper类名(首字母小写)
     -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 指定扫描的包名 
            如果扫描多个包,每个包中间使用半角逗号分隔
        -->
        <property name="basePackage" value="com.cjw.mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>

    </bean>






</beans>

4.  测试类

package com.cjw.test;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.cjw.mapper.UserMapper;
import com.cjw.ssm.po.User;

public class UserDaoImplTest {

   private ApplicationContext applicationContext;

   //SetUp这个方法得到Spring容器
   @Before
   public void setUp() throws Exception {
      applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
   }

   @Test
   public void testFindUserById() throws Exception {

      UserMapper userMapper=(UserMapper) applicationContext.getBean("userMapper");
      //调用userDao的方法
      User user=userMapper.findUserById(1);
      System.out.println(user);

   }
}


四、MyBatis逆向工程


方式一:导入jar包

        逆向工程,这里采用代码生成

        下载逆向工程https://github.com/mybatis/generator/releases/tag/mybatis-generator-1.3.2

        使用方法  :

               ①创建generator配置文件;

               ②使用java类来执行逆向工程;

               ③把生成的代码拷贝到项目中。

               ④ 在正式项目中使用逆向工程生成的代码

        导入jar包



1.  配置文件: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="testTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/mybatis"
                        userId="root"
                        password="root">
        </jdbcConnection>
        <!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
            connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg" 
            userId="yycg"
            password="yycg">
        </jdbcConnection> -->

        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 
            NUMERIC 类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- targetProject:生成PO类的位置 -->
        <javaModelGenerator targetPackage="com.cjw.ssm.po"
                            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.cjw.ssm.mapper"
                         targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="cn.itcast.ssm.mapper"
                             targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!-- 指定数据库表 -->
        <table tableName="items"></table>
        <table tableName="orders"></table>
        <table tableName="orderdetail"></table>
        <table tableName="user"></table>
        <!-- <table schema="" tableName="sys_user"></table>
        <table schema="" tableName="sys_role"></table>
        <table schema="" tableName="sys_permission"></table>
        <table schema="" tableName="sys_user_role"></table>
        <table schema="" tableName="sys_role_permission"></table> -->

        <!-- 有些表的字段需要指定java类型
         <table schema="" tableName="">
            <columnOverride column="" javaType="" />
        </table> -->
    </context>
</generatorConfiguration>

2.  运行java代码

import java.io.File;
import java.io.IOException;
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.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

public class GeneratorSqlmap {

   public void generator() throws Exception{

      List<String> warnings = new ArrayList<String>();
      boolean overwrite = true;
      //指定 逆向工程配置文件
      File configFile = new File("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);

   }
   public static void main(String[] args) throws Exception {
      try {
         GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
         generatorSqlmap.generator();
      } catch (Exception e) {
         e.printStackTrace();
      }

   }

}

3.  使用生成的代码

如果正式项目中已经有po类所在的包了,那么就只需要拷贝po类到指定包下就可以。

如果正式项目中没有po包,那么就把逆向工程中整个po类的包拷贝过去。

Mapper.xml和mapper.java的拷贝与po类一样。

package cn.itcast.ssm.mapper;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.itcast.ssm.po.Items;
import cn.itcast.ssm.po.ItemsExample;

public class ItemsMapperTest {

   private ApplicationContext applicationContext;

   private ItemsMapper itemsMapper;

   //在setUp这个方法得到spring容器
   @Before
   public void setUp() throws Exception {
      applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
      itemsMapper = (ItemsMapper) applicationContext.getBean("itemsMapper");
   }

   //根据主键删除 
   @Test
   public void testDeleteByPrimaryKey() {

   }

   //插入
   @Test
   public void testInsert() {
      //构造 items对象
      Items items = new Items();
      items.setName("手机");
      items.setPrice(999f);
      itemsMapper.insert(items);
   }

   //自定义条件查询
   @Test
   public void testSelectByExample() {
      ItemsExample itemsExample = new ItemsExample();
      //通过criteria构造查询条件
      ItemsExample.Criteria criteria = itemsExample.createCriteria();
      criteria.andNameEqualTo("笔记本3");
      //可能返回多条记录
      List<Items> list = itemsMapper.selectByExample(itemsExample);

      System.out.println(list);

   }

   //根据主键查询
   @Test
   public void testSelectByPrimaryKey() {
      Items items = itemsMapper.selectByPrimaryKey(1);
      System.out.println(items);
   }

   //更新数据
   @Test
   public void testUpdateByPrimaryKey() {

      //对所有字段进行更新,需要先查询出来再更新
      Items items = itemsMapper.selectByPrimaryKey(1);

      items.setName("水杯");

      itemsMapper.updateByPrimaryKey(items);
      //如果传入字段不空为才更新,在批量更新中使用此方法,不需要先查询再更新
      //itemsMapper.updateByPrimaryKeySelective(record);

   }

}

注意事项

    Mapper.xml文件已经存在时,如果进行重新生成则mapper.xml文件时,内容不被覆盖而是进行内容追加,结果导致mybatis解析失败。

解决方法:删除原来已经生成的mapper xml文件再进行生成。

Mybatis自动生成的po及mapper.java文件不是内容而是直接覆盖没有此问题。


方式二:maven整合


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>com.cjw</groupId>
	<artifactId>myBatisGenerator</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<properties>
		<mybatis.version>3.2.8</mybatis.version>
		<mysql.version>5.1.36</mysql.version>
		<mysql-connector-java.version>5.1.28</mysql-connector-java.version>
		<log4j.version>1.2.17</log4j.version>
		<!-- Encoding -->
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<!-- 数据库驱动包 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql-connector-java.version}</version>
		</dependency>
		<!-- mybatis核心包 -->  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis</artifactId>  
            <version>${mybatis.version}</version>  
        </dependency>
		<dependency>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-core</artifactId>
			<version>1.3.2</version>
		</dependency>
		 <!-- 日志文件管理包 -->  
        <dependency>  
            <groupId>log4j</groupId>  
            <artifactId>log4j</artifactId>  
            <version>${log4j.version}</version>  
        </dependency>
	</dependencies>
	<build>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-compiler-plugin</artifactId>
					<configuration>
						<source>1.7</source>
						<target>1.7</target>
					</configuration>
					<version>3.2</version>
				</plugin>
				<plugin>
					<groupId>org.mybatis.generator</groupId>
					<artifactId>mybatis-generator-maven-plugin</artifactId>
					<version>1.3.2</version>
					<configuration>
						<!--配置文件的路径 -->
						<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
						<overwrite>true</overwrite>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>

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="testTables" targetRuntime="MyBatis3">
		<commentGenerator>
			<!-- 是否去除自动生成的注释 true:是 : false:否 -->
			<property name="suppressAllComments" value="true" />
		</commentGenerator>
		<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql://localhost:3306/ssm"
			userId="root"
			password="root">
		</jdbcConnection>
		<!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
			connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg" 
			userId="yycg"
			password="yycg">
		</jdbcConnection> -->

		<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 
			NUMERIC 类型解析为java.math.BigDecimal -->
		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>

		<!-- targetProject:生成PO类的位置 -->
		<javaModelGenerator targetPackage="com.cjw.ssm.po"
			targetProject=".\src\main\java">
			<!-- enableSubPackages:是否让schema作为包的后缀 -->
			<property name="enableSubPackages" value="false" />
			<!-- 从数据库返回的值被清理前后的空格 -->
			<property name="trimStrings" value="true" />
		</javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置 -->
		<sqlMapGenerator targetPackage="com.cjw.ssm.mapper" 
			targetProject=".\src\main\java">
			<!-- enableSubPackages:是否让schema作为包的后缀 -->
			<property name="enableSubPackages" value="false" />
		</sqlMapGenerator>
		<!-- targetPackage:mapper接口生成的位置 -->
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="com.cjw.ssm.mapper" 
			targetProject=".\src\main\java">
			<!-- enableSubPackages:是否让schema作为包的后缀 -->
			<property name="enableSubPackages" value="false" />
		</javaClientGenerator>
		<!-- 指定数据库表 -->
		<table tableName="items"></table>
		<table tableName="orders"></table>
		<table tableName="orderdetail"></table>
		<table tableName="user"></table>
		<!-- <table schema="" tableName="sys_user"></table>
		<table schema="" tableName="sys_role"></table>
		<table schema="" tableName="sys_permission"></table>
		<table schema="" tableName="sys_user_role"></table>
		<table schema="" tableName="sys_role_permission"></table> -->
		
		<!-- 有些表的字段需要指定java类型
		 <table schema="" tableName="">
			<columnOverride column="" javaType="" />
		</table> -->
	</context>
</generatorConfiguration>

运行java代码:GeneratorSqlmap.java

package com.cjw.utils;
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 GeneratorSqlmap {

	public void generator() throws Exception{

		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);

	} 
	public static void main(String[] args) throws Exception {
		try {
			GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
			generatorSqlmap.generator();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}


猜你喜欢

转载自blog.csdn.net/WangFengFans/article/details/80368031