mybatis需要编写sql语句,mybatis官方提供提箱工程,可以针对单表自动生成mybatis执行所需要的代码(诸如bean、dao、mapper),提高工作效率,尤其是在需要大量表进行单表查询的时候,效率极高,快速搭建项目框架的福音。
一、Example + Criteria简介
Example类指定如何构建一个动态的where子句,表中的每个non-BLOB列可以被包括在where子句中。
Example类可以用来生成一个几乎无限的where子句。
Example类包含一个内部静态类 Criteria 包含一个用 anded 组合在where子句中的条件列表。Example类包含一个 List 属性,所有内部类Criteria中的子句会用 ored组合在一起,使用不同属性的 Criteria 类允许您生成无限类型的where子句.。
创建 Criteria 对象 可以使用Example类中的 createCriteria() 或者 or(), 如果 Criteria 对象是用 createCriteria() 创建的,它会自动为 List 属性添加一个 Criteria 对象 - 这使得它更容易写一个简单的where子句, 如果您不需要 or 或者其他几个子句组合的话,用 or(Criteria criteria) 方法创建 Criteria 对象,方法里的 criteria 对象会被添加进 Criteria 对象的列表中。
二、创建SpringBoot工程,添加POM
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.guor</groupId>
<artifactId>MyBatisGenerator</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>MyBatisGenerator</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.20</version>
</dependency>
<dependency>
<groupId>cn.easyproject</groupId>
<artifactId>orai18n</artifactId>
<version>12.1.0.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
三、配置文件
1、application.properties
spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
spring.datasource.username=mine
spring.datasource.password=mine
2、逆向工程模板,此博客的核心
<?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="DB2Tables" targetRuntime="Mybatis3">
<!-- 避免生成重复代码的插件 -->
<!-- <plugin type="com.vi.tmall.util.OverlsMergeablePlugin"/>-->
<!-- 是否不生成注释 -->
<commentGenerator>
<property name="suppressDate" value="true" />
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库链接地址账号密码-->
<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:orcl"
userId="mine" password="mine"/>
<!-- 这个元素的配置用来指定JDBC类型和Java类型如何转换。 -->
<javaTypeResolver>
<!-- 是否强制将DECIMAL和NUMERIC类型的字段转换为Java类型的java.math.BigDecimal -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- targetPackage:生成实体类存放的包名,
targetProject:指定目标项目路径,可以是绝对路径或相对路径(如 targetProject="src/main/java")-->
<javaModelGenerator targetPackage="com.guor.entity" targetProject="src/main/java">
<!--enableSubPackages 如果true,MBG会根据catalog和schema来生成子包。如果false就会直接用targetPackage属性。默认为false-->
<property name="enableSubPackages" value="true"/>
<!-- trimStrings:是否对数据库查询结果进行trim操作,如果设置为true就会生成类似这样public void setUsername(String username)-->
<property name="trimString" value="true" />
</javaModelGenerator>
<!--生成xml映射文件存放位置-->
<sqlMapGenerator targetPackage="com.guor.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!--生成mapper类存放位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.guor.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<table tableName="student" />
<!--生成对应表及类名,enableXXX:XXX代表多种SQL方法,该属性用来指定是否生成对应的XXX语句-->
<!-- <table tableName="student" domainObjectName="Category" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false">
<property name="my.isgen.usekeys" value="true"/>
useActualColumnNames:如果设置为true,那么MBG会使用从数据库元数据获取的列名作为生成的实体对象的属性。 如果为false(默认值),MGB将会尝试将返回的名称转换为驼峰形式
<property name="useActualColumnNames" value="true"/>
<generatedKey column="id" sqlStatement="JDBC"/>
</table> -->
</context>
</generatorConfiguration>
四、加载generator.xml模板
package com.guor;
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 MybatisGenerator {
public static void main(String[] args) throws Exception {
File file = new File("src/generator.xml");
System.out.println("开始逆向!!!");
List<String> warnings = new ArrayList<String>();
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(file);
DefaultShellCallback callback = new DefaultShellCallback(true);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
System.out.println("生成代码成功");
}
}
执行main方法,生成代码。
五、创建controller,进行测试
1、controller
package com.guor.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.guor.entity.Student;
import com.guor.entity.StudentExample;
import com.guor.entity.StudentExample.Criteria;
import com.guor.mapper.StudentMapper;
@Controller
@RequestMapping("/generator")
public class StudentController {
@Autowired
private StudentMapper mapper;
@RequestMapping(path = "/getStudents", method=RequestMethod.GET)
public Student getStudents(){
Student student = mapper.selectByPrimaryKey((short)1);
System.out.println(student);
return student;
}
@RequestMapping(path = "/getStudentsByExample", method=RequestMethod.GET)
public void getStudentsByExample(){
StudentExample example = new StudentExample();
Criteria criteria = example.createCriteria();
criteria.andAgeBetween((short)18, (short)28);
criteria.andNameLike("%k%");
Criteria criteria2 = example.createCriteria();
criteria2.andNameLike("%j%");
example.or(criteria2);//相当于where (age>18 and age<28 and name like '%k%') or name like '%j%';
List<Student> list = mapper.selectByExample(example);
System.out.println(list);
}
}