1. 程式人生 > 資料庫 >實訓三筆記 mybatis動態SQL和generator自動生成程式碼

實訓三筆記 mybatis動態SQL和generator自動生成程式碼

目錄

mybatis動態SQL和generator自動生成程式碼

mybatis動態SQL

1. 匯入依賴pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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.icis</groupId>
    <artifactId>mybatis03</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--統一定義版本號-->
        <properties>
            <spring.version>4.3.9.RELEASE</spring.version>
            <junit.version>4.13</junit.version>
            <mysql.version>5.1.39</mysql.version>
            <druid.version>1.0.9</druid.version>
        </properties>
        <dependencies>
            <!--匯入Spring的核心依賴包-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!--匯入Spring-aspects-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!--匯入junit-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
            </dependency>
            <!--Spring整合junit依賴包-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!--匯入Spring對jdbc操作依賴的包-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!--Spring對事務的支援-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!--資料庫驅動依賴包-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>
            <!--資料庫連線池依賴包-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>${druid.version}</version>
            </dependency>

            <!-- mybatis依賴 -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.0</version>
            </dependency>

            <!-- MySQL資料庫依賴 -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.26</version>
            </dependency>

            <!--日誌 start-->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
            <!--日誌end-->

        </dependencies>

    <build>
        <plugins>
            <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>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
                <executions>
                    <execution>
                        <id>Generate MyBatis Artifacts</id>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.2</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

    
</project>

2. 新建介面EmpDao.java

package com.icis.dao;

import com.icis.pojo.Empl;
import org.apache.ibatis.annotations.Insert;

import java.util.List;

public interface EmpDao {
    Empl getEmpById(Integer empId);
//    Integer empId;
//    String empName;
//    Double empSalary;
//    Date empIntime;
//    Integer empDeptId;
    @Insert("INSERT INTO emp(emp_id, emp_name, emp_salary, emp_intime, emp_dept_id) VALUES (NULL, #{empName}, #{empSalary}, #{empIntime}, #{empDeptId})")
    Integer insertEmpByEmp(Empl empl);


    List<Empl> getAllEmp(Empl empl);

    //批量新增資料
    Integer batchInsertEmp(List<Empl> list);

    //批量刪除
    Integer batchDeleteEmpById(List<Integer> list);

}

4. 新建EmpDao.xml

1. 使用where拼接
<select id="getAllEmp" parameterType="com.icis.pojo.Empl" resultType="com.icis.pojo.Empl">
    --         使用<where></where>拼接動態sql
    SELECT * FROM emp
    <where>
        <if test="empName!='' and empName!=null">
            AND empName LIKE #{empName}
        </if>
        <if test="empSex!='' and empSex!=null">
            AND empSex = #{empSex}
        </if>
    </where>
</select>
2. 動態批量刪除 delete
<!--動態sql批量刪除-->
<!--delete from where id in(1, 2, 3)-->
<delete id="batchDeleteEmpById" parameterType="list">
    DELETE FROM emp WHERE emp_id
    <foreach collection="list" item="id" separator="," open="IN(" close=") ">
        #{id}
    </foreach>
</delete>
3. sql片段引入
<!--sql片段-->
<sql id="myselect">
    select * from
</sql>
<!--引入sql片段-->
<select id="getEmpById" parameterType="int" resultType="com.icis.pojo.Empl">
    <include refid="myselect"></include> emp WHERE emp_id=#{empId}
</select>

4. 動態sql迴圈遍歷list插入

<!--sql片段-->
<sql id="myselect">
    select * from
</sql>
<!--引入sql片段-->
<select id="getEmpById" parameterType="int" resultType="com.icis.pojo.Empl">
    <include refid="myselect"></include> emp WHERE emp_id=#{empId}
</select>

<?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 相當於java語言中的包 (用以防止sql語句名稱衝突)實現sql語句隔離
namespace 一定要和介面名UserDao.java相同
 -->
<mapper namespace="com.icis.dao.EmpDao">
    <!--id要和函式名相同 resultType="user" 可以使用別名-->
    <select id="getAllEmp" parameterType="com.icis.pojo.Empl" resultType="com.icis.pojo.Empl">
--         使用<where></where>拼接動態sql
        SELECT * FROM emp
        <where>
            <if test="empName!='' and empName!=null">
                AND empName LIKE #{empName}
            </if>
            <if test="empSex!='' and empSex!=null">
                AND empSex = #{empSex}
            </if>
        </where>
    </select>

    <!--動態sql批量刪除-->
    <!--delete from where id in(1, 2, 3)-->
    <delete id="batchDeleteEmpById" parameterType="list">
        DELETE FROM emp WHERE emp_id
        <foreach collection="list" item="id" separator="," open="IN(" close=") ">
            #{id}
        </foreach>
    </delete>


    <!--sql片段-->
    <sql id="myselect">
        select * from
    </sql>
    <!--引入sql片段-->
    <select id="getEmpById" parameterType="int" resultType="com.icis.pojo.Empl">
        <include refid="myselect"></include> emp WHERE emp_id=#{empId}
    </select>


    <!--動態sql迴圈遍歷list插入-->
    <insert id="batchInsertEmp" parameterType="list">
        INSERT into emp VALUES
        <foreach collection="list" item="emp" separator=",">
            (null, #{emp.empName}, #{emp.empSalary}, #{emp.empIntime}, #{emp.empDeptId}, #{emp.empSex})
        </foreach>
    </insert>

    <!--List<User> getUserByName(@Param("vo") QueryVo vo);-->
    <!--<select id="getUserByName" resultType="com.icis.pojo.User">-->
        <!--SELECT * FROM user WHERE username LIKE #{vo.username} limit #{vo.idx},#{vo.pageSize}-->
    <!--</select>-->

    <!--通過resultMap把User欄位和資料庫欄位對應起來-->
    <!--<resultMap id="userMap" type="com.icis.pojo.User">-->
        <!--<id column="id" property="id"></id> &lt;!&ndash;主鍵用id&ndash;&gt;-->
        <!--<result column="username" property="username"></result>-->
        <!--<result column="birthday" property="birthday"></result>-->
        <!--<result column="sex" property="sex"></result>-->
        <!--<result column="address" property="address"></result>-->
    <!--</resultMap>-->
    <!--<select id="getUserByName" resultMap="userMap">-->
         <!--SELECT * FROM user WHERE username LIKE #{vo.username} limit #{vo.idx},#{vo.pageSize}-->
    <!--</select>-->

</mapper>

使用mybatis_generator自動生成mapper

1. 引入maven依賴

<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.3.2</version>
</dependency>

完整pom.xml如下

<?xml version="1.0" encoding="UTF-8"?>
<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.icis</groupId>
    <artifactId>mybatis03</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--統一定義版本號-->
    <properties>
        <spring.version>4.3.9.RELEASE</spring.version>
        <junit.version>4.13</junit.version>
        <mysql.version>5.1.39</mysql.version>
        <druid.version>1.0.9</druid.version>
    </properties>
    <dependencies>
        <!--匯入Spring的核心依賴包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--匯入Spring-aspects-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--匯入junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>
        <!--Spring整合junit依賴包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--匯入Spring對jdbc操作依賴的包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--Spring對事務的支援-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--資料庫驅動依賴包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <!--資料庫連線池依賴包-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>

        <!-- mybatis依賴 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.0</version>
        </dependency>

        <!-- MySQL資料庫依賴 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
        </dependency>

        <!--日誌 start-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!--日誌end-->

        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <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>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
                <executions>
                    <execution>
                        <id>Generate MyBatis Artifacts</id>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.2</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

</project>

2. 新建配置檔案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>
	<!--<properties resource="jdbc.properties"></properties>-->
	<!--mysql 連線資料庫jar 這裡選擇自己本地位置-->
	<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/db4" userId="root"
						password="root">
		</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.icis.pojo"
							targetProject="C:\Users\majiao\Desktop\majiao">
			<!-- enableSubPackages:是否讓schema作為包的字尾 -->
			<property name="enableSubPackages" value="false" />
			<!-- 從資料庫返回的值被清理前後的空格 -->
			<property name="trimStrings" value="true" />
		</javaModelGenerator>
		<!-- targetProject:mapper對映檔案生成的位置
           如果maven工程只是單獨的一個工程,targetProject="src/main/java"
           若果maven工程是分模組的工程,targetProject="所屬模組的名稱",例如:
           targetProject="ecps-manager-mapper",下同-->
		<sqlMapGenerator targetPackage="com.icis.mapper"
						 targetProject="C:\Users\majiao\Desktop\majiao">
			<!-- enableSubPackages:是否讓schema作為包的字尾 -->
			<property name="enableSubPackages" value="false" />
		</sqlMapGenerator>
		<!-- targetPackage:mapper介面生成的位置 -->
		<javaClientGenerator type="XMLMAPPER"
							 targetPackage="com.icis.mapper"
							 targetProject="C:\Users\majiao\Desktop\majiao">
			<!-- enableSubPackages:是否讓schema作為包的字尾 -->
			<property name="enableSubPackages" value="false" />
		</javaClientGenerator>
		<!-- 指定資料庫表 -->
		<table schema="" tableName="user"></table>
		<table schema="" tableName="orders"></table>
	</context>
</generatorConfiguration>

3. 新建java檔案GeneratorSqlmap.java編譯執行

即可在輸出目錄看見mapper



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("G:\\Xubuntu_Work_Space\\From_Xubuntu\\codeTest_2019_2_21\\IDEA\\Maven_Pojos\\mybatis03自動生成dao層\\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();
		}
		
	}

}

4. 把生成的實體類和mapper.xml複製到對應目錄即可