1、引入MyBatista包
<!--MyBatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
2、注解版使用
//指定这是一个操作数据库的mapper
@Mapper
public interface DeptMapper {
@Select("select * from dept where id = #{id}")
public Dept getDeptById(Integer id);
@Delete("delete from dept where id =#{id}")
public int deleteById(Integer id);
//自增主键需要加@Options注解 useGeneratedKeys=true 表示启用 keyProperty表示要自增的字段
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into dept(user_name) values(#{userName})")
public int insterDept(Dept dept);
@Update("update dept set user_name= #{userName} where id = #{id}")
public int updateDept(Dept dept);
}
如果字段是驼峰命名的,需要这样配置,就可以支持驼峰命名了,不然查询会报错
首先在config文件创建一个MyBatisConfig,生成自定义MyBatis的配置规则;给容器中添加一个configurationCustomizer;
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(Configuration configuration) {
//开启驼峰命名规则
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
使用MapperScan 批量扫描所有的Mapper接口
@MapperScan(value = "com.ykk.springboot.mapper")
3、配置文件版使用
mybatis官方文档中文地址https://mybatis.org/mybatis-3/zh/index.html
MyBatis全局配置文件
mybatis:
config-location: classpath:mybatis/mybatis-config.xml 指定全局配置文件的位置
mapper-locations: classpath:mybatis/mapper/*.xml 指定sql映射文件的地址
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>
<settings>
<!--解决,查询返回结果含null没有对应字段值问题-->
<setting name="callSettersOnNulls" value="true"/>
<!--是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
sql映射文件
<?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">
<mapper namespace="com.ykk.springboot.mapper.DeptNewMapper">自己的mapper地址
<!--如果设置了resultMap 就无须在mybatis-config里面开启驼峰了-->
<resultMap id="roleMap" type="com.ykk.springboot.bean.Dept" >自己的bean地址
<id column="id" property="id" javaType="long" jdbcType="BIGINT" />
<result column="role_name" property="roleName" javaType="string"
jdbcType="VARCHAR" />
<result column="note" property="note"
typeHandler="com.gethin.handler.MyStringHandler" />
</resultMap>
<select id="getRole" parameterType="long" resultMap="roleMap">
select
id,role_name as roleName,note from role where id=#{id}
</select>
<select id="findRole" parameterType="long" resultMap="roleMap">
select
id,role_name,note from role where role_name like CONCAT('%',#{roleName
javaType=string,
jdbcType=VARCHAR,typeHandler=com.gethin.handler.MyStringHandler},'%')
</select>
<insert id="insertRole" parameterType="role">
insert into
role(role_name,note) value(#{roleName},#{note})
</insert>
<delete id="deleteRole" parameterType="long">
delete from role where
id=#{id}
</delete>
</mapper>
4、集成Mybatis Generator
maven方式配置
运行Mybatis Generator插件,采用maven的方式,在pom.xml文件中加入
<!--引用MyBatis Generator的jar包-->
<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.3</version>
</dependency>
<!--Mybatis Generator插件-->
<!--引入mybatis生成器-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.0</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
</dependencies>
</plugin>
generatorConfig.xml配置文件
创建一个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="MysqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
<!--自动生成序列化-->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
<!--自动生成toString-->
<plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
<!-- 这里的type里写的是你的实现类的类全类名,注:如果不配置type属性,则会使用默认的CommentGenerator实现类DefaultCommentGenerator -->
<commentGenerator type="com.ykk.springboot.config.MyGenerator">
<!-- 去除自动生成的注释 -->
<!-- <property name="suppressAllComments" value="true" /> -->
<!-- 是否生成注释代时间戳-->
<!--<property name="suppressDate" value="true"/>-->
</commentGenerator>
<!--数据库连接URL,用户名,密码-->
<!-- 数据库连接 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://192.168.16.105:6606/c_lease_ty?serverTimezone=Asia/Shanghai"
userId="c_lease_ty"
password="lease_ty" />
<!--生成模型的包名和位置,对应数据库的实体类-->
<!-- model生成 -->
<javaModelGenerator targetPackage="com.ykk.springboot.model" targetProject="src/main/java" >
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!--生成映射文件的包名和位置,也就是生成的对应的xml文件的位置-->
<!-- MapperXML生成 -->
<sqlMapGenerator targetPackage="com.ykk.springboot.mapper" targetProject="src/main/java" >
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- Mapper接口生成 -->
<javaClientGenerator targetPackage="com.ykk.springboot.mapper" targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 需要映射的表 tableName是数据库中的表明或视图名 domainObjectName是实体类名称
如果不想生成example(例子)可以设置下面的属性为false
enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false"
-->
<table tableName="test" domainObjectName="Test"
enableCountByExample="false" enableDeleteByExample="false"
enableUpdateByExample="false" enableSelectByExample="false">
</table>
</context>
</generatorConfiguration>
运行generator
generator功能优化
成功后可以看到默认的英文注释说明了类属性所对应的数据库字段,但是没有拿到数据库中定义的注释。
CommentGenerator接口的实现类
1、自定义一个CommentGenerator接口的实现类
package com.ykk.springboot.config;
import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.MergeConstants;
import org.mybatis.generator.config.PropertyRegistry;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
public class MyGenerator implements CommentGenerator {
private Properties properties;
private Properties systemPro;
private boolean suppressDate;
private boolean suppressAllComments;
private String nowTime;
public MyGenerator() {
super();
properties = new Properties();
systemPro = System.getProperties();
suppressDate = false;
suppressAllComments = false;
nowTime = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date());
}
public void addJavaFileComment(CompilationUnit compilationUnit) {
if (suppressAllComments) {
return;
}
return;
}
/**
* 添加适当的注释以警告用户该元素已生成,并且
* 当它生成时
*/
public void addComment(XmlElement xmlElement) {
return;
}
public void addRootComment(XmlElement rootElement) {
// add no document level comments by default
return;
}
public void addConfigurationProperties(Properties properties) {
this.properties.putAll(properties);
suppressDate = isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE));
suppressAllComments = isTrue(properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS));
}
/**
* 判断传入参数是否为true
*/
private boolean isTrue(String property) {
if("true".equals(property)){
return true;
}
return false;
}
/**
* 此方法为添加自定义javadoc标记。
* 如果你做了,你可能什么也不做不希望包含Javadoc标记-但是,
* 如果不包含Javadoc标记,那么eclipse插件的Java合并功能将休息。
* @param javaElement
* java元素
*/
protected void addJavadocTag(JavaElement javaElement, boolean markAsDoNotDelete) {
javaElement.addJavaDocLine(" *");
StringBuilder sb = new StringBuilder();
sb.append(" * ");
sb.append(MergeConstants.NEW_ELEMENT_TAG);
if (markAsDoNotDelete) {
sb.append(" do_not_delete_during_merge");
}
String s = getDateString();
if (s != null) {
sb.append(' ');
sb.append(s);
}
javaElement.addJavaDocLine(sb.toString());
}
/**
* 此方法返回要包含在Javadoc标记中的格式化日期字符串
* 和XML注释。如果不想输入日期,可以返回null
* 这些文档元素。
*
* @return 表示当前时间戳的字符串,或null
*/
protected String getDateString() {
String result = null;
if (!suppressDate) {
result = nowTime;
}
return result;
}
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
innerClass.addJavaDocLine("/**");
sb.append(" * ");
sb.append(introspectedTable.getFullyQualifiedTable());
sb.append(" ");
sb.append(getDateString());
innerClass.addJavaDocLine(sb.toString().replace("\n", " "));
innerClass.addJavaDocLine(" */");
}
public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
innerEnum.addJavaDocLine("/**");
sb.append(" * ");
sb.append(introspectedTable.getFullyQualifiedTable());
innerEnum.addJavaDocLine(sb.toString().replace("\n", " "));
innerEnum.addJavaDocLine(" */");
}
/**
* 设置字段注释
*/
public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
field.addJavaDocLine("/**");
sb.append(" * ");
sb.append(introspectedColumn.getRemarks() + " " + introspectedColumn.getActualColumnName());
field.addJavaDocLine(sb.toString().replace("\n", " "));
field.addJavaDocLine(" */");
}
public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
field.addJavaDocLine("/**");
sb.append(" * ");
sb.append(introspectedTable.getFullyQualifiedTable());
field.addJavaDocLine(sb.toString().replace("\n", " "));
field.addJavaDocLine(" */");
}
public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
}
public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
method.addJavaDocLine("/**");
addJavadocTag(method, false);
method.addJavaDocLine(" */");
}
/**
* 设置getter方法注释
*/
public void addGetterComment(Method method, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
if (suppressAllComments) {
return;
}
method.addJavaDocLine("/**");
StringBuilder sb = new StringBuilder();
sb.append(" * ");
sb.append(introspectedColumn.getRemarks());
method.addJavaDocLine(sb.toString().replace("\n", " "));
sb.setLength(0);
//加入系统用户
sb.append(" * @author ");
sb.append(systemPro.getProperty("user.name"));
method.addJavaDocLine(sb.toString().replace("\n", " "));
sb.setLength(0);
//是否加入时间戳
if(suppressDate){
sb.append(" * @date " + nowTime);
method.addJavaDocLine(sb.toString().replace("\n", " "));
sb.setLength(0);
}
sb.append(" * @return ");
sb.append(introspectedColumn.getActualColumnName());
sb.append(" ");
sb.append(introspectedColumn.getRemarks());
method.addJavaDocLine(sb.toString().replace("\n", " "));
method.addJavaDocLine(" */");
}
/**
* 设置setter方法注释
*/
public void addSetterComment(Method method, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
if (suppressAllComments) {
return;
}
method.addJavaDocLine("/**");
StringBuilder sb = new StringBuilder();
sb.append(" * ");
sb.append(introspectedColumn.getRemarks());
method.addJavaDocLine(sb.toString().replace("\n", " "));
sb.setLength(0);
//加入系统用户
sb.append(" * @author ");
sb.append(systemPro.getProperty("user.name"));
method.addJavaDocLine(sb.toString().replace("\n", " "));
sb.setLength(0);
//是否加入时间戳
if(suppressDate){
sb.append(" * @date " + nowTime);
method.addJavaDocLine(sb.toString().replace("\n", " "));
sb.setLength(0);
}
Parameter parm = method.getParameters().get(0);
sb.append(" * @param ");
sb.append(parm.getName());
sb.append(" ");
sb.append(introspectedColumn.getRemarks());
method.addJavaDocLine(sb.toString().replace("\n", " "));
method.addJavaDocLine(" */");
}
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
innerClass.addJavaDocLine("/**");
sb.append(" * ");
sb.append(introspectedTable.getFullyQualifiedTable());
innerClass.addJavaDocLine(sb.toString().replace("\n", " "));
sb.setLength(0);
sb.append(" * @author ");
sb.append(systemPro.getProperty("user.name"));
sb.append(" ");
sb.append(nowTime);
innerClass.addJavaDocLine(" */");
}
}
generator配置文件使用
2、在generator配置文件里面使用
<!-- 这里的type里写的是你的实现类的类全类名,注:如果不配置type属性,则会使用默认的CommentGenerator实现类DefaultCommentGenerator -->
<commentGenerator type="com.ykk.springboot.config.MyGenerator">
<!-- 去除自动生成的注释 -->
<!-- <property name="suppressAllComments" value="true" /> -->
<!-- 是否生成注释代时间戳-->
<!--<property name="suppressDate" value="true"/>-->
</commentGenerator>
运行生成
3、启动类
package com.ykk.springboot.config.util;
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;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class RunClass {
public static void main(String[] args) {
try {
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);
} catch (Exception e) {
e.printStackTrace();
}
}
}