本小记学习标
了解MyBatis Generator插件的使用
一、MyBatis Generator
我们在使用Spring集成MyBatis时发现,除了配置外我们还需要编写Dao接口、实体类、Mapping映射文件,这个过程是比较繁琐的,对于这些内容我们可以使用MyBatis Generator插件帮忙我们生成,从而使用我们的更加专注于业务逻辑代码的编写上。
MyBatis Generator有三种常用的方法来自动生成代码
-
命令行
-
Eclipse插件
-
Maven插件
Eclipse插件安装
在线安装插件
1.Help-->Install New Software...
在上面弹出的对话框Name后的输入框中输出一个名称(自定义)、在Location后的输入框中输入在线地址
Name:MyBatis-Generator
Location:https://dl.bintray.com/mybatis/mybatis-generator/
接下来Next--->accept--->install
安装完成后,会提示重新启动Eclipse,在重启完成后可以验证是否安装成功
File--->New--->other--->在向导中输入MyBatis,如果可以看到如下信息则表示安装成功
为了使用方便可以把这个选项集成到New而不需要进入Other中去选择,按如下操作去配置
我们新增一个实例进行测试
我们mysql数据库中存在一个表student,表信息如下:
1.新增一个Maven的jar工程,在对应的pom.xml中新增如下依赖
<
dependencies
>
<!--
mysql
-connector-java -->
<
dependency
>
<
groupId
>
mysql
</
groupId
>
<
artifactId
>
mysql-connector-java
</
artifactId
>
<
version
>5.1.45
</
version
>
</
dependency
>
<!--
mybatis
-->
<
dependency
>
<
groupId
>org.mybatis
</
groupId
>
<
artifactId
>
mybatis
</
artifactId
>
<
version
>3.4.5
</
version
>
</
dependency
>
<
dependency
>
<
groupId
>org.mybatis.dynamic-
sql
</
groupId
>
<
artifactId
>
mybatis-dynamic-
sql
</
artifactId
>
<
version
>1.1.4
</
version
>
</
dependency
>
<
dependency
>
<
groupId
>javax.annotation
</
groupId
>
<
artifactId
>jsr250-
api
</
artifactId
>
<
version
>1.0
</
version
>
</
dependency
>
</
dependencies
>
2.新增配置文件,首先我们新增一个包com.xiaoxie.dao.mybatis.config,在这个包上点击右键选择New-->MyBatis Generator Configuration File,在弹出的对话框中直接点击Finish
3.编辑刚才生成的配置文件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=
"context1"
>
<
jdbcConnection
connectionURL=
"jdbc:mysql://localhost:3306/test?characterEncoding=utf8"
driverClass=
"com.mysql.jdbc.Driver"
password=
"root"
userId=
"root"
/>
<!-- 实体 -->
<
javaModelGenerator
targetPackage=
"com.xiaoxie.pojo"
targetProject=
"SSM_10"
>
<
property
name=
"enableSubPackages"
value=
"true"
/>
</
javaModelGenerator
>
<!-- XMLMapper -->
<
javaClientGenerator
targetPackage=
"com.xiaoxie.dao"
targetProject=
"SSM_10"
type=
"XMLMAPPER"
>
<
property
name=
"enableSubPackages"
value=
"true"
/>
</
javaClientGenerator
>
<
table
schema=
"test"
tableName=
"student"
enableCountByExample=
"true"
enableUpdateByExample=
"true"
enableDeleteByExample=
"true"
enableSelectByExample=
"true"
enableSelectByPrimaryKey=
"true"
>
</
table
>
</
context
>
</
generatorConfiguration
>
配置中主要有四部分信息
(1)由于自动生成时需要读取数据库的信息所以需要配置数据的连接信息
(2)需要指定实体生成在哪里,指定生成的目标包targetPackage
(3) 需要指定xmlMapper生成在哪里,指定生成的目标包targetPackage
(4) 指定数据库及表信息
注意:这里面的配置信息中有一个targetProject,这里指定的是项目的名称,表示在哪个项目中生成,这里不能写错如果找不到则在生成时会出错
4.在刚才编写的这个配置文件上点击右键,选择Run As---->Run MyBatis Generator
运行后会开始根据配置的信息生成对应的信息,并且在控制台会打印出生成的日志信息
MyBatis Generator Started...
Buildfile: D:\STSProject\.metadata\.plugins\org.mybatis.generator.eclipse.ui\.generatedAntScripts\SSM_10-generatorConfig.xml.xml
BUILD SUCCESSFUL
MyBatis Generator Finished
这个时候会生成如下信息:
com.xiaoie.pojo下会生成Student实体类
package com.xiaoxie.pojo;
import javax.annotation.Generated;
public
class Student {
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1263811+08:00", comments =
"Source field: student.ID")
private Integer
id;
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1263811+08:00", comments =
"Source field: student.NAME")
private String
name;
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1273821+08:00", comments =
"Source field: student.AGE")
private Integer
age;
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1263811+08:00", comments =
"Source field: student.ID")
public Integer getId() {
return
id;
}
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1263811+08:00", comments =
"Source field: student.ID")
public
void setId(Integer
id) {
this.
id =
id;
}
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1263811+08:00", comments =
"Source field: student.NAME")
public String getName() {
return
name;
}
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1273821+08:00", comments =
"Source field: student.NAME")
public
void setName(String
name) {
this.
name =
name;
}
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1273821+08:00", comments =
"Source field: student.AGE")
public Integer getAge() {
return
age;
}
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1273821+08:00", comments =
"Source field: student.AGE")
public
void setAge(Integer
age) {
this.
age =
age;
}
/*这个是手工添加的,目的打印对象时可以看到对象信息辨识度更高*/
public String toString() {
return
"Student[id="+
id+
",name="+
name+
",age="+
age+
"]";
}
}
注意:toString方法是手工添加上去的
com.xiaoxie.dao下生成StudentMapper的接口
package com.xiaoxie.dao;
import
static com.xiaoxie.dao.StudentDynamicSqlSupport.*;
import
static org.mybatis.dynamic.sql.SqlBuilder.*;
import com.xiaoxie.pojo.Student;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import javax.annotation.Generated;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.dynamic.sql.BasicColumn;
import org.mybatis.dynamic.sql.delete.DeleteDSLCompleter;
import org.mybatis.dynamic.sql.delete.render.DeleteStatementProvider;
import org.mybatis.dynamic.sql.insert.render.InsertStatementProvider;
import org.mybatis.dynamic.sql.insert.render.MultiRowInsertStatementProvider;
import org.mybatis.dynamic.sql.select.CountDSLCompleter;
import org.mybatis.dynamic.sql.select.SelectDSLCompleter;
import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
import org.mybatis.dynamic.sql.update.UpdateDSL;
import org.mybatis.dynamic.sql.update.UpdateDSLCompleter;
import org.mybatis.dynamic.sql.update.UpdateModel;
import org.mybatis.dynamic.sql.update.render.UpdateStatementProvider;
import org.mybatis.dynamic.sql.util.SqlProviderAdapter;
import org.mybatis.dynamic.sql.util.mybatis3.MyBatis3Utils;
@Mapper
public
interface StudentMapper {
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1323683+08:00", comments =
"Source Table: student")
BasicColumn[] selectList = BasicColumn.columnList(id, name, age);
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1313709+08:00", comments =
"Source Table: student")
@SelectProvider(type = SqlProviderAdapter.
class, method =
"select")
long count(SelectStatementProvider selectStatement);
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1313709+08:00", comments =
"Source Table: student")
@DeleteProvider(type = SqlProviderAdapter.
class, method =
"delete")
int delete(DeleteStatementProvider deleteStatement);
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1313709+08:00", comments =
"Source Table: student")
@InsertProvider(type = SqlProviderAdapter.
class, method =
"insert")
int insert(InsertStatementProvider<Student> insertStatement);
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1313709+08:00", comments =
"Source Table: student")
@InsertProvider(type = SqlProviderAdapter.
class, method =
"insertMultiple")
int insertMultiple(MultiRowInsertStatementProvider<Student> multipleInsertStatement);
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1313709+08:00", comments =
"Source Table: student")
@SelectProvider(type = SqlProviderAdapter.
class, method =
"select")
@ResultMap(
"StudentResult")
Optional<Student> selectOne(SelectStatementProvider selectStatement);
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1313709+08:00", comments =
"Source Table: student")
@SelectProvider(type = SqlProviderAdapter.
class, method =
"select")
@Results(id =
"StudentResult", value = {
@Result(column =
"ID", property =
"id", jdbcType = JdbcType.INTEGER, id =
true),
@Result(column =
"NAME", property =
"name", jdbcType = JdbcType.VARCHAR),
@Result(column =
"AGE", property =
"age", jdbcType = JdbcType.INTEGER) })
List<Student> selectMany(SelectStatementProvider selectStatement);
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1313709+08:00", comments =
"Source Table: student")
@UpdateProvider(type = SqlProviderAdapter.
class, method =
"update")
int update(UpdateStatementProvider updateStatement);
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1313709+08:00", comments =
"Source Table: student")
default
long count(CountDSLCompleter completer) {
return MyBatis3Utils.countFrom(
this::count, student, completer);
}
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1313709+08:00", comments =
"Source Table: student")
default
int delete(DeleteDSLCompleter completer) {
return MyBatis3Utils.deleteFrom(
this::delete, student, completer);
}
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1313709+08:00", comments =
"Source Table: student")
default
int deleteByPrimaryKey(Integer id_) {
return delete(c -> c.where(id, isEqualTo(id_)));
}
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1313709+08:00", comments =
"Source Table: student")
default
int insert(Student record) {
return MyBatis3Utils.insert(
this::insert, record, student,
c -> c.map(id).toProperty(
"id").map(name).toProperty(
"name").map(age).toProperty(
"age"));
}
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1323683+08:00", comments =
"Source Table: student")
default
int insertMultiple(Collection<Student> records) {
return MyBatis3Utils.insertMultiple(
this::insertMultiple, records, student,
c -> c.map(id).toProperty(
"id").map(name).toProperty(
"name").map(age).toProperty(
"age"));
}
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1323683+08:00", comments =
"Source Table: student")
default
int insertSelective(Student record) {
return MyBatis3Utils.insert(
this::insert, record, student,
c -> c.map(id).toPropertyWhenPresent(
"id", record::getId).map(name)
.toPropertyWhenPresent(
"name", record::getName).map(age)
.toPropertyWhenPresent(
"age", record::getAge));
}
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1323683+08:00", comments =
"Source Table: student")
default Optional<Student> selectOne(SelectDSLCompleter completer) {
return MyBatis3Utils.selectOne(
this::selectOne, selectList, student, completer);
}
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1323683+08:00", comments =
"Source Table: student")
default List<Student> select(SelectDSLCompleter completer) {
return MyBatis3Utils.selectList(
this::selectMany, selectList, student, completer);
}
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1323683+08:00", comments =
"Source Table: student")
default List<Student> selectDistinct(SelectDSLCompleter completer) {
return MyBatis3Utils.selectDistinct(
this::selectMany, selectList, student, completer);
}
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1323683+08:00", comments =
"Source Table: student")
default Optional<Student> selectByPrimaryKey(Integer id_) {
return selectOne(c -> c.where(id, isEqualTo(id_)));
}
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1323683+08:00", comments =
"Source Table: student")
default
int update(UpdateDSLCompleter completer) {
return MyBatis3Utils.update(
this::update, student, completer);
}
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1323683+08:00", comments =
"Source Table: student")
static UpdateDSL<UpdateModel> updateAllColumns(Student record, UpdateDSL<UpdateModel> dsl) {
return dsl.set(id).equalTo(record::getId).set(name).equalTo(record::getName).set(age).equalTo(record::getAge);
}
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1323683+08:00", comments =
"Source Table: student")
static UpdateDSL<UpdateModel> updateSelectiveColumns(Student record, UpdateDSL<UpdateModel> dsl) {
return dsl.set(id).equalToWhenPresent(record::getId).set(name).equalToWhenPresent(record::getName).set(age)
.equalToWhenPresent(record::getAge);
}
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1323683+08:00", comments =
"Source Table: student")
default
int updateByPrimaryKey(Student record) {
return update(c -> c.set(name).equalTo(record::getName).set(age).equalTo(record::getAge).where(id,
isEqualTo(record::getId)));
}
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1323683+08:00", comments =
"Source Table: student")
default
int updateByPrimaryKeySelective(Student record) {
return update(c -> c.set(name).equalToWhenPresent(record::getName).set(age).equalToWhenPresent(record::getAge)
.where(id, isEqualTo(record::getId)));
}
}
com.xiaoxie.dao下会生成StudentDynamicSqlSupport
package com.xiaoxie.dao;
import java.sql.JDBCType;
import javax.annotation.Generated;
import org.mybatis.dynamic.sql.SqlColumn;
import org.mybatis.dynamic.sql.SqlTable;
public
final
class StudentDynamicSqlSupport {
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1303739+08:00", comments =
"Source Table: student")
public
static
final Student
student =
new Student();
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1313709+08:00", comments =
"Source field: student.ID")
public
static
final SqlColumn<Integer>
id =
student.
id;
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1313709+08:00", comments =
"Source field: student.NAME")
public
static
final SqlColumn<String>
name =
student.
name;
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1313709+08:00", comments =
"Source field: student.AGE")
public
static
final SqlColumn<Integer>
age =
student.
age;
@Generated(value =
"org.mybatis.generator.api.MyBatisGenerator", date =
"2020-11-24T23:45:23.1303739+08:00", comments =
"Source Table: student")
public
static
final
class Student
extends SqlTable {
public
final SqlColumn<Integer>
id = column(
"ID", JDBCType.
INTEGER);
public
final SqlColumn<String>
name = column(
"NAME", JDBCType.
VARCHAR);
public
final SqlColumn<Integer>
age = column(
"AGE", JDBCType.
INTEGER);
public Student() {
super(
"student");
}
}
}
5.接下来配置MyBatis的配置信息(src/main/resources下)
新增一个jdbc.properties(配置数据库的连接信息)
jdbc.driverClass=
com.mysql.jdbc.Driver
jdbc.url=
jdbc:mysql://
localhost
:3306/test?characterEncoding=utf8
jdbc.username=
root
jdbc.password=
root
新增一个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
>
<!-- 引入外部资源文件 -->
<
properties
resource=
"jdbc.properties"
/>
<!-- 配置
mybatis
的全局环境 -->
<
environments
default=
"development"
>
<
environment
id=
"development"
>
<
transactionManager
type=
"JDBC"
/>
<
dataSource
type=
"POOLED"
>
<!-- 连接信息 -->
<
property
name=
"driver"
value=
"${jdbc.driverClass}"
/>
<
property
name=
"url"
value=
"${jdbc.url}"
/>
<
property
name=
"username"
value=
"${jdbc.username}"
/>
<
property
name=
"password"
value=
"${jdbc.password}"
/>
</
dataSource
>
</
environment
>
</
environments
>
<!-- 映射文件 -->
<
mappers
>
<
mapper
class=
"com.xiaoxie.dao.StudentMapper"
/>
</
mappers
>
</
configuration
>
6.新增测试类com.xiaoxie.test.Application,在其中新增测试方法
@SuppressWarnings(
"deprecation")
private
static
void generatorMybatis()
throws IOException {
String
mybatisConfigPath =
"mybatis-config.xml";
//读取配置文件
InputStream
config = Resources.
getResourceAsStream(
mybatisConfigPath);
//构建SqlSessionFactory
SqlSessionFactory
sqlSessionFactory =
new SqlSessionFactoryBuilder().build(
config);
//创建SqlSession对象
SqlSession
sqlSession =
sqlSessionFactory.openSession();
StudentMapper
studentMapper =
sqlSession.getMapper(StudentMapper.
class);
SelectStatementProvider
selectStatement =
select(
id,
name,
age).from(
student).where().build().render(RenderingStrategy.
MYBATIS3);
List<Student>
students =
studentMapper.selectMany(
selectStatement);
for (Student
stu :
students) {
System.
out.println(
stu);
}
}
7.在main方法中调用上述方法,运行后控制打印结果如下
Student[id=2,name=关公,age=29]
Student[id=3,name=张飞,age=26]
Student[id=10,name=诸葛亮,age=23]
Student[id=11,name=赵云,age=23]
Student[id=12,name=黄忠,age=35]