mybatis逆向工程

逆向工程:根據數據庫表自動生成po類及相應的接口和映射。java

  注意:逆向工程只能生成單個表的po類,可是它並不知道表和表的對應關係。mysql

 Mybatis逆向工程spring

  使用官方網站的mapper自動生成工具mybatis-generator-core-1.3.2來生成po類和mapper映射文件.sql

  做用:mybatis官方提供逆向工程,可使用它經過數據庫中的表來自動生成Mapper接口和映射文件(單表增刪改查)Po.數據庫

  導入的jar包有:api

1.1  第一步:mapper生成配置文件:

在generatorConfig.xml中配置mapper生成的詳細信息,注意改下幾點:mybatis

一、修改鏈接數據庫的數據表,以及用戶名和密碼oracle

二、 添加要生成的數據庫表app

三、 po文件所在包路徑ide

四、 mapper文件所在包路徑

配置文件以下:

 

<?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.huida.po"
            targetProject=".\src">
            <!-- enableSubPackages:是否讓schema做爲包的後綴 -->
            <property name="enableSubPackages" value="false" />
            <!-- 從數據庫返回的值被清理先後的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.huida.mapper" 
            targetProject=".\src">
            <!-- enableSubPackages:是否讓schema做爲包的後綴 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="com.huida.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>

 

 

1.2  第二步:使用java類生成mapper文件:

 

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 StartService {

    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 {
            StartService ss=new StartService();
            ss.generator();
        } catch (Exception e) {
            e.printStackTrace();
        }
}
}

 

1.3 第三步:運行編寫的java類來生成對應的文件

  右擊--->Run As--->Java Application。

  注意這裏應該是應該是Java Application。

1.4  第四步:拷貝生成的mapper文件到工程中指定的目錄中

  好比咱們以前創建一個工程爲:spring-mybatis,咱們當前逆向工程的工程名爲gerneratorDemo,咱們將當前工程下生成的mapper.xml以及mapper接口都複製到咱們spring-mybatis工程下的mapper包下;同時也將當前工程下生成的po類複製到咱們spring-mybatis工程下的po包下。

  注意:mapper.xml文件和mapper.java文件在同一個目錄內且文件名相同。

 

1.5  第五步:Mapper接口測試

  咱們在spring-mybatis工程下建立測試文件進行測試。mapper自動生成了基本的增刪改查方法,如:

 

//刪除符合條件的記錄
int deleteByExample(UserExample example);
//根據主鍵刪除
int deleteByPrimaryKey(String id);
//插入對象全部字段
int insert(User record);
//插入對象不爲空的字段
int insertSelective(User record);
//自定義查詢條件查詢結果集
List<User> selectByExample(UserExample example);
//根據主鍵查詢
UserselectByPrimaryKey(String id);
//根據主鍵將對象中不爲空的值更新至數據庫
int updateByPrimaryKeySelective(User record);
//根據主鍵將對象中全部字段的值更新至數據庫
int updateByPrimaryKey(User record);

 

  咱們若是僅是進行簡單的增刪改查方法,能夠拿過來直接用,可是若是咱們須要進行一些複合查詢,則須要使用他建立的UserExample中po類來傳輸一些條件。

  咱們的測試代碼以下:

package comm.huida.test;


import java.util.List;

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

import com.huida.mapper.UserMapper;
import com.huida.po.User;
import com.huida.po.UserExample;
import com.huida.po.UserExample.Criteria;

public class UserMapperTest {

    private ApplicationContext applicationContext;
    @Before
    public void setUp(){
        applicationContext=new ClassPathXmlApplicationContext("classpath:config/applicationContext.xml");
    }
    /*@Test
    public void testFindUserById(){
        UserMapper userMapper=(UserMapper) applicationContext.getBean("userMapper");
        User user=userMapper.findUserById(1);
        System.out.println(user);
    }*/
    
    @Test
    public void testFindUserById(){
        UserMapper userMapper=(UserMapper) applicationContext.getBean("userMapper");
        User user=userMapper.selectByPrimaryKey(1);
        System.out.println(user);
    }
    /*
     * 經過姓名和性別進行查找
     * 找姓名中包含「li」,性別爲1
     */
    @Test
    public void testFindUserAndSex(){
        UserMapper userMapper=(UserMapper) applicationContext.getBean("userMapper");
        //建立UserExample對象,而且加入條件
        UserExample example=new UserExample();
        Criteria criteria=example.createCriteria();
        //加入條件
        criteria.andUsernameLike("%li%");
        criteria.andSexEqualTo("1");
        List<User> list=userMapper.selectByExample(example);
        System.out.println(list);
    }
}
相關文章
相關標籤/搜索