此为mybatis的用法,plus的用法 点击 进入
xml中使用uuid
1 2 3 <selectKey keyProperty ="key名" resultType ="java.lang.String" order ="BEFORE" > select uuid() </selectKey >
在 中间加上上面段落 keyProperty为insert的id栏位值
1 2 3 4 5 mybatis: mapperLocations: classpath:mapper/*.xml type-aliases-package: com.simplemw.entity configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
使用handler处理字段 mybtis中提供了不同类型的继承BaseTypeHandler的不同类型的handler来处理字段
工作中问题,存入数据在blob中,拿出来的时候乱码,解决办法:使用mybtis的handler直接进行处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 public class MybatisBlobHandler extends BaseTypeHandler <String> { private static final String DEFAULT_CHARSET = "utf-8" ; @Override public void setNonNullParameter (PreparedStatement ps, int i,String parameter, JdbcType jdbcType) throws SQLException { ByteArrayInputStream bis; try { bis = new ByteArrayInputStream (parameter.getBytes(DEFAULT_CHARSET)); } catch (UnsupportedEncodingException e) { throw new RuntimeException ("Blob Encoding Error!" ); } ps.setBinaryStream(i, bis, parameter.length()); } @Override public String getNullableResult (ResultSet rs, String columnName) throws SQLException { Blob blob = (Blob) rs.getBlob(columnName); byte [] returnValue = null ; if (null != blob) { returnValue = blob.getBytes(1 , (int ) blob.length()); } try { return new String (returnValue, DEFAULT_CHARSET); } catch (UnsupportedEncodingException e) { throw new RuntimeException ("Blob Encoding Error!" ); } } @Override public String getNullableResult (CallableStatement cs, int columnIndex) throws SQLException { Blob blob = (Blob) cs.getBlob(columnIndex); byte [] returnValue = null ; if (null != blob) { returnValue = blob.getBytes(1 , (int ) blob.length()); } try { return new String (returnValue, DEFAULT_CHARSET); } catch (UnsupportedEncodingException e) { throw new RuntimeException ("Blob Encoding Error!" ); } } @Override public String getNullableResult (ResultSet rs, int columnIndex) throws SQLException { return null ; } }
1 @TableField(typeHandler = MybatisBlobHandler.class)
理解:
BaseTypeHandler 中存在4个方法,一个set与三个get(通过列名从结果集中获取字段,通过下标从结果集中获取字段,还有一个专用于存储过程(吾目前没用过))
setNonNullParameter(),mybatis中的sql执行是以预编译的形式,上面的实现原理就是在insert之前对数据进行处理然后放入PreparedStatement中
getNullableResult(),查询结果出来后,获取查询的信息,对其中的信息做处理然后返回至pojo对象中
使用pagehelper分页 实现原理就是在执行的sql后面添加 limit(pageNum,pageSize)
1 2 3 4 5 <dependency > <groupId > com.github.pagehelper</groupId > <artifactId > pagehelper-spring-boot-starter</artifactId > <version > 1.2.12</version > </dependency >
1 2 3 4 5 6 7 8 9 10 11 pagehelper: helperDialect: mysql reasonable: true pageSizeZero: true supportMethodsArguments: true autoRuntimeDialect: true
1 2 PageHelper.startPage(pageNum,pageSize);
注:若xml中配置了 supportMethodsArguments:true,则在Dao层方法的参数列表中直接添加pageNum和pageSize可以自动识别分页
pagehelper 补充 mybatisplus 使用pagehelper分页
mybatisplus自带了pagehelper不用注入依赖
添加配置类
1 2 3 4 5 6 7 8 @Configuration public class MybatisPlus { @Bean public PaginationInterceptor paginationInterceptor () { PaginationInterceptor paginationInterceptor = new PaginationInterceptor (); return paginationInterceptor; } }
1 2 3 4 5 6 7 8 9 pagehelper: reasonable: true pageSizeZero: true supportMethodsArguments: true autoRuntimeDialect: true
mapper配置(plus中需要mapper去继承BaseMapper)
1 2 3 @Mapper public interface PrintTemplateMapper extends BaseMapper <PrintTemplate> {}
1 2 3 4 5 6 7 QueryWrapper<PrintTemplate> queryWrapper = new QueryWrapper <>(); Page<PrintTemplate> page = new Page <>(pageIndex, pageSize); queryWrapper.eq("id" , "123" ); printTemplateMapper.selectPage(page, queryWrapper);
代码生成器 两种方式:启动类,plugin插件
启动类
1 2 3 4 5 6 <dependency > <groupId > org.mybatis.generator</groupId > <artifactId > mybatis-generator-core</artifactId > <version > 1.3.6</version > </dependency >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 <?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 > <classPathEntry location ="D:\maven\mysql\mysql-connector-java\8.0.15\mysql-connector-java-8.0.15.jar" /> <context id ="mysql" targetRuntime ="MyBatis3" > <property name ="javaFileEncoding" value ="UTF-8" /> <property name ="javaFormatter" value ="org.mybatis.generator.api.dom.DefaultJavaFormatter" /> <property name ="xmlFormatter" value ="org.mybatis.generator.api.dom.DefaultXmlFormatter" /> <plugin type ="org.mybatis.generator.plugins.SerializablePlugin" > </plugin > <commentGenerator > <property name ="suppressAllComments" value ="true" /> </commentGenerator > <jdbcConnection driverClass ="com.mysql.cj.jdbc.Driver" connectionURL ="jdbc:mysql://localhost:3306/cloud_data?useUnicode=true& characterEncoding=utf-8& useSSL=true& serverTimezone=UTC" userId ="root" password ="123456" > </jdbcConnection > <javaTypeResolver > <property name ="forceBigDecimals" value ="false" /> </javaTypeResolver > <javaModelGenerator targetProject ="./src/main/java" targetPackage ="com.simplemw.entity" > <property name ="enableSubPackages" value ="true" /> <property name ="trimStrings" value ="true" /> </javaModelGenerator > <javaClientGenerator targetProject ="./src/main/java" targetPackage ="com.simplemw.dao" type ="XMLMAPPER" > <property name ="enableSubPackages" value ="true" /> </javaClientGenerator > <sqlMapGenerator targetProject ="./src/main/resources" targetPackage ="mapper" > <property name ="enableSubPackages" value ="true" /> </sqlMapGenerator > <table tableName ="dept" domainObjectName ="Dept" enableCountByExample ="false" enableUpdateByExample ="false" enableDeleteByExample ="false" enableSelectByExample ="false" selectByExampleQueryId ="false" > <property name ="useActualColumnNames" value ="false" /> </table > </context > </generatorConfiguration >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class generator { public static void main (String[] args) throws Exception{ 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 ); } }
plugin插件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <plugin > <groupId > org.mybatis.generator</groupId > <artifactId > mybatis-generator-maven-plugin</artifactId > <version > 1.4.0</version > <executions > <execution > <id > Generate MyBatis Artifacts</id > <goals > <goal > generate</goal > </goals > </execution > </executions > <configuration > <verbose > true</verbose > <overwrite > true</overwrite > <configurationFile > ${basedir}/src/main/resources/generatorConfig.xml</configurationFile > </configuration > </plugin >
注:generatorConfig.xml中需要加入本地的数据库连接jar地址
1 <classPathEntry location ="D:\maven\mysql\mysql-connector-java\8.0.15\mysql-connector-java-8.0.15.jar" />
Mybatis时间格式化
1 date_format(now(), '%Y-%m-%d %H:%i:%s')
1 @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
1 2 @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JSONField(format="yyyy-MM-dd")
Mybatis查询补充 in
1 2 3 4 id in <foreach collection ="ids" index ="index" item ="item" open ="(" separator ="," close =")" > #{item} </foreach >
open=”(“ separator=”,” close=”)” 拼接括号参数
index=”index” 确定foreach的起始位置,类似于游标的功能
collection=”ids” 传入的list名称
item=”item” 每一个元素的名称
if else
1 2 3 4 5 6 7 8 9 10 11 <choose > <when test ="condition == 1" > AND name = #{name1} </when > <when test ="condition == 2" > AND name = #{name2} </when > <otherwise > AND name = #{name3} </otherwise > </choose >
1 2 3 4 5 6 7 if (condition == 1 ){ AND name = #{name1} }else if (condition == 2 ){ AND name = #{name2} }else { AND name = #{name3} }
#{}和${} 1 2 #{} 预编译(最终带单引号) ${} 直接获取(不带单引号) 若需要加单引号可使用 <![CDATA['${id}' ]]>
注 判断相等时,后面的字符串要加toString()
1 2 3 4 5 6 7 8 9 10 11 <choose > <when test ="condition == '1'.toString()" > AND name = #{name1} </when > <when test ="condition == '2'.toString()" > AND name = #{name2} </when > <otherwise > AND name = #{name3} </otherwise > </choose >