
- 外文名
- MyBatis
- 时 间
- 2010年
- 单 位
- Github
- 来 源
- apache
- 运行平台
- java
- 原 名
- iBatis
-
Mybatis使用IN语句查询
2018-03-23 16:45:03一、简介在SQL语法中如果我们想使用in的话直接可以像如下一样使用:select * from HealthCoupon where useType in ( '4' , '3' )但是如果在MyBatis中的使用in的话,像如下去做的话,肯定会报错: Map<String, ...一、简介
在SQL语法中如果我们想使用in的话直接可以像如下一样使用:
select * from HealthCoupon where useType in ( '4' , '3' )
但是如果在MyBatis中的使用in的话,像如下去做的话,肯定会报错:
Map<String, Object> selectByUserId(@Param("useType") String useType) <select id="selectByUserId" resultMap="BaseResultMap" parameterType="java.lang.String"> select * from HealthCoupon where useType in (#{useType,jdbcType=VARCHAR}) </select>
其中useType="2,3";这样的写法,看似很简单,但是MyBatis不支持这样操作,可以用$进行替换,如下方式即可运行
Map<String, Object> selectByUserId(@Param("useType") String useType) <select id="selectByUserId" resultMap="BaseResultMap" parameterType="java.lang.String"> select * from HealthCoupon where useType in (${useType,jdbcType=VARCHAR}) </select>
#方式能够很大程度防止sql注入,$方式无法防止sql注入,所以还是推荐使用#方式,参考以下三种方式。
MyBatis中提供了foreach语句实现IN查询,foreach语法如下:
foreach语句中, collection属性的参数类型可以使:List、数组、map集合 collection: 必须跟mapper.java中@Param标签指定的元素名一样 item: 表示在迭代过程中每一个元素的别名,可以随便起名,但是必须跟元素中的#{}里面的名称一样。 index:表示在迭代过程中每次迭代到的位置(下标) open:前缀, sql语句中集合都必须用小括号()括起来 close:后缀 separator:分隔符,表示迭代时每个元素之间以什么分隔
正确的写法有以下几种写法:
(一)、selectByIdSet(List idList)
如果参数的类型是List, 则在使用时,collection属性要必须指定为 list
List<User> selectByIdSet(List idList); <select id="selectByIdSet" resultMap="BaseResultMap"> SELECT <include refid="Base_Column_List" /> from t_user WHERE id IN <foreach collection="list" item="id" index="index" open="(" close=")" separator=","> #{id} </foreach> </select>
(二)、List<User> selectByIdSet(String[] idList)如果参数的类型是Array,则在使用时,collection属性要必须指定为 array
List<User> selectByIdSet(String[] idList); <select id="selectByIdSet" resultMap="BaseResultMap"> SELECT <include refid="Base_Column_List" /> from t_user WHERE id IN <foreach collection="array" item="id" index="index" open="(" close=")" separator=","> #{id} </foreach> </select>
(三)、参数有多个时当查询的参数有多个时,有两种方式可以实现,一种是使用@Param("xxx")进行参数绑定,另一种可以通过Map来传参数。
3.1 @Param("xxx")方式
List<User> selectByIdSet(@Param("name")String name, @Param("ids")String[] idList); <select id="selectByIdSet" resultMap="BaseResultMap"> SELECT <include refid="Base_Column_List" /> from t_user WHERE name=#{name,jdbcType=VARCHAR} and id IN <foreach collection="ids" item="id" index="index" open="(" close=")" separator=","> #{id} </foreach> </select>
3.2 Map方式
Map<String, Object> params = new HashMap<String, Object>(2); params.put("name", name); params.put("idList", ids); mapper.selectByIdSet(params); <select id="selectByIdSet" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from t_user where name = #{name} and ID in <foreach item="item" index="index" collection="idList" open="(" separator="," close=")"> #{item} </foreach> </select>
-
Mybatis-Plus和Mybatis的区别
2019-04-01 11:09:50Mybatis-Plus是一个Mybatis的增强工具,它在Mybatis的基础上做了增强,却不做改变。我们在使用Mybatis-Plus之后既可以使用Mybatis-Plus的特有功能,又能够正常使用Mybatis的原生功能。Mybatis-Plus(以下简称MP)是为...原文:https://blog.csdn.net/qq_34508530/article/details/88943858
.
.
.
.
.
.区别一
如果Mybatis Plus是扳手,那Mybatis Generator就是生产扳手的工厂。
通俗来讲——
MyBatis:一种操作数据库的框架,提供一种Mapper类,支持让你用java代码进行增删改查的数据库操作,省去了每次都要手写sql语句的麻烦。但是!有一个前提,你得先在xml中写好sql语句,是不是很麻烦?于是有下面的↓
Mybatis Generator:自动为Mybatis生成简单的增删改查sql语句的工具,省去一大票时间,两者配合使用,开发速度快到飞起。至于标题说的↓
Mybatis Plus:国人团队苞米豆在Mybatis的基础上开发的框架,在Mybatis基础上扩展了许多功能,荣获了2018最受欢迎国产开源软件第5名,当然也有配套的↓
Mybatis Plus Generator:同样为苞米豆开发,比Mybatis Generator更加强大,支持功能更多,自动生成Entity、Mapper、Service、Controller等
总结:
数据库框架:Mybatis Plus > Mybatis
代码生成器:Mybatis Plus Generator > Mybatis Generator
.
.
.
.
.区别二
Mybatis-Plus是一个Mybatis的增强工具,它在Mybatis的基础上做了增强,却不做改变。我们在使用Mybatis-Plus之后既可以使用Mybatis-Plus的特有功能,又能够正常使用Mybatis的原生功能。Mybatis-Plus(以下简称MP)是为简化开发、提高开发效率而生,但它也提供了一些很有意思的插件,比如SQL性能监控、乐观锁、执行分析等。
Mybatis虽然已经给我们提供了很大的方便,但它还是有不足之处,实际上没有什么东西是完美的,MP的存在就是为了稍稍弥补Mybatis的不足。在我们使用Mybatis时会发现,每当要写一个业务逻辑的时候都要在DAO层写一个方法,再对应一个SQL,即使是简单的条件查询、即使仅仅改变了一个条件都要在DAO层新增一个方法,针对这个问题,MP就提供了一个很好的解决方案,之后我会进行介绍。另外,MP的代码生成器也是一个很有意思的东西,它可以让我们避免许多重复性的工作,下面我将介绍如何在你的项目中集成MP。
.
.
.
.
.一、 集成步骤↓:(首先,你要有个spring项目)
集成依赖,pom中加入依赖即可,不多说:
Java代码 收藏代码<!-- mybatis mybatis-plus mybatis-spring mvc --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>${mybatis-plus.version}</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.0</version> </dependency>
说明:笔者使用的版本为:mybatis-plus.version=2.1-gamma,上边的代码中有两个依赖,第一个是mybatis-plus核心依赖,第二个是使用代码生成器时需要的模板引擎依赖,若果你不打算使用代码生成器,此处可不引入。
注意:mybatis-plus的核心jar包中已集成了mybatis和mybatis-spring,所以为避免冲突,请勿再次引用这两个jar包。.
.
.二、 在spring中配置MP:
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean"> <!-- 配置数据源 --> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描 Xml 文件位置 --> <property name="mapperLocations" value="classpath*:com/ds/orm/mapper/**/*.xml" /> <!-- 配置 Mybatis 配置文件(可无) --> <property name="configLocation" value="classpath:mybatis-config.xml" /> <!-- 配置包别名,支持通配符 * 或者 ; 分割 --> <property name="typeAliasesPackage" value="com.ds.orm.model" /> <!-- 枚举属性配置扫描,支持通配符 * 或者 ; 分割 --> <!-- <property name="typeEnumsPackage" value="com.baomidou.springmvc.entity.*.enums" /> --> <!-- 以上配置和传统 Mybatis 一致 --> <!-- MP 全局配置注入 --> <property name="globalConfig" ref="globalConfig" /> </bean>
<bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration"> <!-- 主键策略配置 --> <!-- 可选参数 AUTO->`0`("数据库ID自增") INPUT->`1`(用户输入ID") ID_WORKER->`2`("全局唯一ID") UUID->`3`("全局唯一ID") --> <property name="idType" value="2" /> <!-- 数据库类型配置 --> <!-- 可选参数(默认mysql) MYSQL->`mysql` ORACLE->`oracle` DB2->`db2` H2->`h2` HSQL->`hsql` SQLITE->`sqlite` POSTGRE->`postgresql` SQLSERVER2005->`sqlserver2005` SQLSERVER->`sqlserver` --> <property name="dbType" value="mysql" /> <!-- 全局表为下划线命名设置 true --> <property name="dbColumnUnderline" value="true" /> <property name="sqlInjector"> <bean class="com.baomidou.mybatisplus.mapper.AutoSqlInjector" /> </property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <description>DAO接口所在包名,Spring会自动查找其下的类</description> <property name="basePackage" value="com.ds.orm.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 乐观锁插件 --> <bean class="com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor" /> <!-- xml mapper热加载 sqlSessionFactory:session工厂 mapperLocations:mapper匹配路径 enabled:是否开启动态加载 默认:false delaySeconds:项目启动延迟加载时间 单位:秒 默认:10s sleepSeconds:刷新时间间隔 单位:秒 默认:20s --> <bean class="com.baomidou.mybatisplus.spring.MybatisMapperRefresh"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" /> <constructor-arg name="mapperLocations" value="classpath*:com/ds/orm/mapper/*/*.xml" /> <constructor-arg name="delaySeconds" value="10" /> <constructor-arg name="sleepSeconds" value="20" /> <constructor-arg name="enabled" value="true" /> </bean> <!-- 事务 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> 注意:只要做如上配置就可以正常使用mybatis了,不要重复配置。MP的配置和mybatis一样,都是配置一个sqlSessionFactory,只是现在所配置的类在原本的SqlSessionFactoryBean基础上做了增强。插件等配置请按需取舍。 插件配置,按需求配置就可以,此处把可以配置的插件都列了出来,具体的请看代码注释: <configuration> <settings> <setting name="logImpl" value="SLF4J" /> <!-- 字段为空时仍调用model的set方法或map的put方法 --> <setting name="callSettersOnNulls" value="true" /> </settings> <plugins> <!-- | 分页插件配置 | 插件提供二种方言选择:1、默认方言 2、自定义方言实现类,两者均未配置则抛出异常! | overflowCurrent 溢出总页数,设置第一页 默认false | optimizeType Count优化方式 ( 版本 2.0.9 改为使用 jsqlparser 不需要配置 ) | --> <!-- 注意!! 如果要支持二级缓存分页使用类 CachePaginationInterceptor 默认、建议如下!! --> <plugin interceptor="com.baomidou.mybatisplus.plugins.PaginationInterceptor"> <property name="dialectType" value="mysql" /> <!--<property name="sqlParser" ref="自定义解析类、可以没有" /> <property name="localPage" value="默认 false 改为 true 开启了 pageHeper 支持、可以没有" /> <property name="dialectClazz" value="自定义方言类、可以没有" /> --> </plugin> <!-- SQL 执行性能分析,开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长 --> <plugin interceptor="com.baomidou.mybatisplus.plugins.PerformanceInterceptor"> <property name="maxTime" value="2000" /> <!--SQL是否格式化 默认false --> <property name="format" value="true" /> </plugin> <!-- SQL 执行分析拦截器 stopProceed 发现全表执行 delete update 是否停止运行 该插件只用于开发环境,不建议生产环境使用。。。 --> <plugin interceptor="com.baomidou.mybatisplus.plugins.SqlExplainInterceptor"> <property name="stopProceed" value="false" /> </plugin> </plugins> </configuration>
注意:执行分析拦截器和性能分析推荐只在开发时调试程序使用,为保证程序性能和稳定性,建议在生产环境中注释掉这两个插件。
数据源:(此处使用druid)<!-- 配置数据源 --> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- <property name="driverClassName" value="${jdbc.driverClassName}" /> --> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="initialSize" value="${jdbc.initialSize}" /> <property name="minIdle" value="${jdbc.minIdle}" /> <property name="maxActive" value="${jdbc.maxActive}" /> <property name="maxWait" value="${jdbc.maxWait}" /> <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" /> <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" /> <property name="validationQuery" value="${jdbc.validationQuery}" /> <property name="testWhileIdle" value="${jdbc.testWhileIdle}" /> <property name="testOnBorrow" value="${jdbc.testOnBorrow}" /> <property name="testOnReturn" value="${jdbc.testOnReturn}" /> <property name="removeAbandoned" value="${jdbc.removeAbandoned}" /> <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" /> <!-- <property name="logAbandoned" value="${jdbc.logAbandoned}" /> --> <property name="filters" value="${jdbc.filters}" /> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true" /> <property name="proxyFilters"> <list> <ref bean="log-filter"/> </list> </property> <!-- 监控数据库 --> <!-- <property name="filters" value="stat" /> --> <!-- <property name="filters" value="mergeStat" />--> </bean>
到此,MP已经集成进我们的项目中了,下面将介绍它是如何简化我们的开发的。
.
.
.**
三、 简单的CURD操作↓:
**
假设我们有一张user表,且已经建立好了一个与此表对应的实体类User,我们来介绍对user的简单增删改查操作。
建立DAO层接口。我们在使用普通的mybatis时会建立一个DAO层接口,并对应一个xml用来写SQL。在这里我们同样要建立一个DAO层接口,但是若无必要,我们甚至不需要建立xml,就可以进行资源的CURD操作了,我们只需要让我们建立的DAO继承MP提供的BaseMapper<?>即可:public interface UserMapper extends BaseMapper { }
然后在我们需要做数据CURD时,像下边这样就好了:
Java代码 收藏代码
// 初始化 影响行数
int result = 0;
// 初始化 User 对象
User user = new User();// 插入 User (插入成功会自动回写主键到实体类)
user.setName(“Tom”);
result = userMapper.insert(user);// 更新 User
user.setAge(18);
result = userMapper.updateById(user);//user要设置id哦,具体的在下边我会详细介绍// 查询 User
User exampleUser = userMapper.selectById(user.getId());// 查询姓名为‘张三’的所有用户记录
List userList = userMapper.selectList(
new EntityWrapper().eq(“name”, “张三”)
);// 删除 User
result = userMapper.deleteById(user.getId());方便吧?如果只使用mybatis可是要写4个SQL和4个方法喔,当然了,仅仅上边这几个方法还远远满足不了我们的需求,请往下看:
.
.**
多条件分页查询:
**
// 分页查询 10 条姓名为‘张三’、性别为男,且年龄在18至50之间的用户记录List<User> userList = userMapper.selectPage( new Page<User>(1, 10), new EntityWrapper<User>().eq("name", "张三") .eq("sex", 0) .between("age", "18", "50") );
/**等价于SELECT *
*FROM sys_user
*WHERE (name=‘张三’ AND sex=0 AND age BETWEEN ‘18’ AND ‘50’)
*LIMIT 0,10
*/
.
.
.
下边这个,多条件构造器。其实对于条件过于复杂的查询,笔者还是建议使用原生mybatis的方式实现,易于维护且逻辑清晰,如果所有的数据操作都强行使用MP,就失去了MP简化开发的意义了。所以在使用时请按实际情况取舍,在这里还是先介绍一下。public Page<T> selectPage(Page<T> page, EntityWrapper<T> entityWrapper) { if (null != entityWrapper) { entityWrapper.orderBy(page.getOrderByField(), page.isAsc());//排序 } page.setRecords(baseMapper.selectPage(page, entityWrapper));//将查询结果放入page中 return page; }
** 条件构造一(上边方法的entityWrapper参数):**
public void testTSQL11() { /* * 实体带查询使用方法 输出看结果 */ EntityWrapper<User> ew = new EntityWrapper<User>(); ew.setEntity(new User(1)); ew.where("user_name={0}", "'zhangsan'").and("id=1") .orNew("user_status={0}", "0").or("status=1") .notLike("user_nickname", "notvalue") .andNew("new=xx").like("hhh", "ddd") .andNew("pwd=11").isNotNull("n1,n2").isNull("n3") .groupBy("x1").groupBy("x2,x3") .having("x1=11").having("x3=433") .orderBy("dd").orderBy("d1,d2"); System.out.println(ew.getSqlSegment()); }
.
.
.
** 条件构造二(同上):**int buyCount = selectCount(Condition.create()
.setSqlSelect(“sum(quantity)”)
.isNull(“order_id”)
.eq(“user_id”, 1)
.eq(“type”, 1)
.in(“status”, new Integer[]{0, 1})
.eq(“product_id”, 1)
.between(“created_time”, startDate, currentDate)
.eq(“weal”, 1));
自定义条件使用entityWrapper:List selectMyPage(RowBounds rowBounds, @Param(“ew”) Wrapper wrapper);
SELECT * FROM user ${ew.sqlSegment} *注意:此处不用担心SQL注入,MP已对ew做了字符串转义处理。 其实在使用MP做数据CURD时,还有另外一个方法,AR(ActiveRecord ),很简单,让我们的实体类继承MP提供Model<?>就好了,这和我们常用的方法可能会有些不同,下边简单说一下吧:*.
.
.
.
//实体类
@TableName(“sys_user”) // 注解指定表名
public class User extends Model {… // fields
… // getter and setter
.
./ 指定主键 /*
@Override
protected Serializable pkVal() { //一定要指定主键哦
return this.id;
}
}
.
.
.
下边就是CURD操作了:// 初始化 成功标识
boolean result = false;
// 初始化 User
User user = new User();// 保存 User
user.setName(“Tom”);
result = user.insert();// 更新 User
user.setAge(18);
result = user.updateById();// 查询 User
User exampleUser = t1.selectById();// 查询姓名为‘张三’的所有用户记录
List userList1 = user.selectList(
new EntityWrapper().eq(“name”, “张三”)
);// 删除 User
result = t2.deleteById();// 分页查询 10 条姓名为‘张三’、性别为男,且年龄在18至50之间的用户记录
List userList = user.selectPage(
new Page(1, 10),
new EntityWrapper().eq(“name”, “张三”)
.eq(“sex”, 0)
.between(“age”, “18”, “50”)
).getRecords();
就是这样了,可能你会说MP封装的有些过分了,这样做会分散数据逻辑到不同的层面中,难以管理,使代码难以理解。其实确实是这样,这就需要你在使用的时候注意一下了,在简化开发的同时也要保证你的代码层次清晰,做一个战略上的设计或者做一个取舍与平衡。
.
.
.
.
.
.**
其实上边介绍的功能也不是MP的全部啦,下边介绍一下MP最有意思的模块——代码生成器。
**
步骤↓:
如上边所说,使用代码生成器一定要引入velocity-engine-core(模板引擎)这个依赖。
准备工作:
选择主键策略,就是在上边最开始时候我介绍MP配置时其中的这项配置,如果你不记得了,请上翻!MP提供了如下几个主键策略: 值 描述
IdType.AUTO ----------数据库ID自增
IdType.INPUT ----------用户输入ID
IdType.ID_WORKER---------- 全局唯一ID,内容为空自动填充(默认配置)
IdType.UUID ----------全局唯一ID,内容为空自动填充
MP默认使用的是ID_WORKER,这是MP在Sequence的基础上进行部分优化,用于产生全局唯一ID。表及字段命名策略选择,同上,还是在那个配置中。下边这段复制至MP官方文档:
在MP中,我们建议数据库表名采用下划线命名方式,而表字段名采用驼峰命名方式。这么做的原因是为了避免在对应实体类时产生的性能损耗,这样字段不用做映射就能直接和实体类对应。当然如果项目里不用考虑这点性能损耗,那么你采用下滑线也是没问题的,只需要在生成代码时配置dbColumnUnderline属性就可以。
建表(命名规则依照刚才你所配置的,这会影响生成的代码的类名、字段名是否正确)。
执行下边的main方法,生成代码:import java.util.HashMap; import java.util.Map; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.DataSourceConfig; import com.baomidou.mybatisplus.generator.config.GlobalConfig; import com.baomidou.mybatisplus.generator.config.PackageConfig; import com.baomidou.mybatisplus.generator.config.StrategyConfig; import com.baomidou.mybatisplus.generator.config.rules.DbType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; /** * <p> * 代码生成器演示 * </p> */ public class MpGenerator { /** * <p> * MySQL 生成演示 * </p> */ public static void main(String[] args) { AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); gc.setOutputDir("D://"); gc.setFileOverride(true); gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false gc.setEnableCache(false);// XML 二级缓存 gc.setBaseResultMap(true);// XML ResultMap gc.setBaseColumnList(false);// XML columList // .setKotlin(true) 是否生成 kotlin 代码 gc.setAuthor("Yanghu"); // 自定义文件命名,注意 %s 会自动填充表实体属性! // gc.setMapperName("%sDao"); // gc.setXmlName("%sDao"); // gc.setServiceName("MP%sService"); // gc.setServiceImplName("%sServiceDiy"); // gc.setControllerName("%sAction"); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setTypeConvert(new MySqlTypeConvert(){ // 自定义数据库表字段类型转换【可选】 @Override public DbColumnType processTypeConvert(String fieldType) { System.out.println("转换类型:" + fieldType); // 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。 return super.processTypeConvert(fieldType); } }); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("521"); dsc.setUrl("jdbc:mysql://127.0.0.1:3306/mybatis-plus?characterEncoding=utf8"); mpg.setDataSource(dsc); // 策略配置 StrategyConfig strategy = new StrategyConfig(); // strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意 strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });// 此处可以修改为您的表前缀 strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略 // strategy.setInclude(new String[] { "user" }); // 需要生成的表 // strategy.setExclude(new String[]{"test"}); // 排除生成的表 // 自定义实体父类 // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity"); // 自定义实体,公共字段 // strategy.setSuperEntityColumns(new String[] { "test_id", "age" }); // 自定义 mapper 父类 // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper"); // 自定义 service 父类 // strategy.setSuperServiceClass("com.baomidou.demo.TestService"); // 自定义 service 实现类父类 // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl"); // 自定义 controller 父类 // strategy.setSuperControllerClass("com.baomidou.demo.TestController"); // 【实体】是否生成字段常量(默认 false) // public static final String ID = "test_id"; // strategy.setEntityColumnConstant(true); // 【实体】是否为构建者模型(默认 false) // public User setName(String name) {this.name = name; return this;} // strategy.setEntityBuilderModel(true); mpg.setStrategy(strategy); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent("com.baomidou"); pc.setModuleName("test"); mpg.setPackageInfo(pc); // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { Map<String, Object> map = new HashMap<String, Object>(); map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp"); this.setMap(map); } }; // 自定义 xxList.jsp 生成 List<FileOutConfig> focList = new ArrayList<FileOutConfig>(); focList.add(new FileOutConfig("/template/list.jsp.vm") { @Override public String outputFile(TableInfo tableInfo) { // 自定义输入文件名称 return "D://my_" + tableInfo.getEntityName() + ".jsp"; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 调整 xml 生成目录演示 focList.add(new FileOutConfig("/templates/mapper.xml.vm") { @Override public String outputFile(TableInfo tableInfo) { return "/develop/code/xml/" + tableInfo.getEntityName() + ".xml"; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 关闭默认 xml 生成,调整生成 至 根目录 TemplateConfig tc = new TemplateConfig(); tc.setXml(null); mpg.setTemplate(tc); // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改, // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称 // TemplateConfig tc = new TemplateConfig(); // tc.setController("..."); // tc.setEntity("..."); // tc.setMapper("..."); // tc.setXml("..."); // tc.setService("..."); // tc.setServiceImpl("..."); // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。 // mpg.setTemplate(tc); // 执行生成 mpg.execute(); // 打印注入设置【可无】 System.err.println(mpg.getCfg().getMap().get("abc")); } }
说明:中间的内容请自行修改,注释很清晰。
成功生成代码,将生成的代码拷贝到你的项目中就可以了,这个东西节省了我们大量的时间和精力!**
.
.
.
.
.
.以下是注解说明,摘自官方文档: 注解说明**
表名注解 @TableName
com.baomidou.mybatisplus.annotations.TableName
值 描述
value ---------- 表名( 默认空 )
resultMap ---------- xml 字段映射 resultMap ID主键注解 @TableId
com.baomidou.mybatisplus.annotations.TableId
值 描述
value ---------- 字段值(驼峰命名方式,该值可无)
type ----------主键 ID 策略类型( 默认 INPUT ,全局开启的是 ID_WORKER )
暂不支持组合主键字段注解 @TableField
com.baomidou.mybatisplus.annotations.TableField
值 描述
value ----------字段值(驼峰命名方式,该值可无)
el ---------- 详看注释说明
exist ----------是否为数据库表字段( 默认 true 存在,false 不存在 )
strategy ---------- 字段验证 ( 默认 非 null 判断,查看 com.baomidou.mybatisplus.enums.FieldStrategy )
.
fill ----------字段填充标记 ( FieldFill, 配合自动填充使用 )
字段填充策略 FieldFill
值 描述
DEFAULT ----------默认不处理
INSERT ----------插入填充字段
UPDATE ----------更新填充字段
INSERT_UPDATE ----------插入和更新填充字段序列主键策略 注解 @KeySequence
com.baomidou.mybatisplus.annotations.KeySequence
值 描述
value ----------序列名
clazz ----------id的类型
乐观锁标记注解 ----------@Versioncom.baomidou.mybatisplus.annotations.Version
排除非表字段、查看文档常见问题部分!总结:MP的宗旨是简化开发,但是它在提供方便的同时却容易造成代码层次混乱,我们可能会把大量数据逻辑写到service层甚至contoller层中,使代码难以阅读。凡事过犹不及,在使用MP时一定要做分析,不要将所有数据操作都交给MP去实现。毕竟MP只是mybatis的增强工具,它并没有侵入mybatis的原生功能,在使用MP的增强功能的同时,原生mybatis的功能依然是可以正常使用的
-
mybatis trim标签的使用
2018-07-11 17:04:51mybatis trim标签一般用于去除sql语句中多余的and关键字,逗号,或者给sql语句拼接where、set等前缀mybatis的trim标签一般用于去除sql语句中多余的and关键字,逗号,或者给sql语句前拼接 “where“、“set“以及“values(“ 等前缀,或者添加“)“等后缀,可用于选择性插入、更新、删除或者条件查询等操作。
以下是trim标签中涉及到的属性:属性 描述 prefix 给sql语句拼接的前缀 suffix 给sql语句拼接的后缀 prefixOverrides 去除sql语句前面的关键字或者字符,该关键字或者字符由prefixOverrides属性指定,假设该属性指定为"AND",当sql语句的开头为"AND",trim标签将会去除该"AND" suffixOverrides 去除sql语句后面的关键字或者字符,该关键字或者字符由suffixOverrides属性指定 下面使用几个例子来说明trim标签的使用。
1、使用trim标签去除多余的and关键字
有这样的一个例子:
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE <if test="state != null"> state = #{state} </if> <if test="title != null"> AND title like #{title} </if> <if test="author != null and author.name != null"> AND author_name like #{author.name} </if> </select>
如果这些条件没有一个能匹配上会发生什么?最终这条 SQL 会变成这样:
SELECT * FROM BLOG WHERE
这会导致查询失败。如果仅仅第二个条件匹配又会怎样?这条 SQL 最终会是这样:
SELECT * FROM BLOG WHERE AND title like ‘someTitle’
你可以使用where标签来解决这个问题,where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入“WHERE”子句。而且,若语句的开头为“AND”或“OR”,where 元素也会将它们去除。
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG <where> <if test="state != null"> state = #{state} </if> <if test="title != null"> AND title like #{title} </if> <if test="author != null and author.name != null"> AND author_name like #{author.name} </if> </where> </select>
trim标签也可以完成相同的功能,写法如下:
<trim prefix="WHERE" prefixOverrides="AND"> <if test="state != null"> state = #{state} </if> <if test="title != null"> AND title like #{title} </if> <if test="author != null and author.name != null"> AND author_name like #{author.name} </if> </trim>
2、使用trim标签去除多余的逗号
有如下的例子:
如果红框里面的条件没有匹配上,sql语句会变成如下:
INSERT INTO role(role_name,) VALUES(roleName,)
插入将会失败。
使用trim标签可以解决此问题,只需做少量的修改,如下所示:
其中最重要的属性是
suffixOverrides=","
表示去除sql语句结尾多余的逗号.
注:如果你有兴趣的话,可以研究下Mybatis逆向工程生成的Mapper文件。其中也使用了trim标签,但结合了foreach、choose等标签,更多的是牵扯到Criterion的源码研究。不过研究完之后,你将熟练掌握mybatis各种标签的使用,学到Criterion的设计思想,对自己的启发将会很大。
如果想要了解更多关余trim标签的内容,请移步《trim标签源码解析》。本文参考 Mybatis官方文档
-
Mybatis工作原理
2018-06-24 00:16:53在mybatis的基础知识中我们已经可以对mybatis的工作方式窥斑见豹(参考:《MyBatis————基础知识》)。 本片博客针对Mybatis内部工作原理进行阐述。 一、Mybatis工作原理图 mybatis 原理图如下所示: 二、...引言
在mybatis的基础知识中我们已经可以对mybatis的工作方式窥斑见豹(参考:《MyBatis————基础知识》)。
本片博客针对Mybatis内部工作原理进行阐述。
一、Mybatis工作原理图
mybatis 原理图如下所示:
二、工作原理解析
mybatis应用程序通过SqlSessionFactoryBuilder从mybatis-config.xml配置文件(也可以用Java文件配置的方式,需要添加@Configuration)来构建SqlSessionFactory(SqlSessionFactory是线程安全的);
然后,SqlSessionFactory的实例直接开启一个SqlSession,再通过SqlSession实例获得Mapper对象并运行Mapper映射的SQL语句,完成对数据库的CRUD和事务提交,之后关闭SqlSession。
说明:SqlSession是单线程对象,因为它是非线程安全的,是持久化操作的独享对象,类似jdbc中的Connection,底层就封装了jdbc连接。
详细流程如下:
1、加载mybatis全局配置文件(数据源、mapper映射文件等),解析配置文件,MyBatis基于XML配置文件生成Configuration,和一个个MappedStatement(包括了参数映射配置、动态SQL语句、结果映射配置),其对应着<select | update | delete | insert>标签项。
2、SqlSessionFactoryBuilder通过Configuration对象生成SqlSessionFactory,用来开启SqlSession。
3、SqlSession对象完成和数据库的交互:
a、用户程序调用mybatis接口层api(即Mapper接口中的方法)
b、SqlSession通过调用api的Statement ID找到对应的MappedStatement对象
c、通过Executor(负责动态SQL的生成和查询缓存的维护)将MappedStatement对象进行解析,sql参数转化、动态sql拼接,生成jdbc Statement对象
d、JDBC执行sql。e、借助MappedStatement中的结果映射关系,将返回结果转化成HashMap、JavaBean等存储结构并返回。
mybatis层次图:
原图:https://blog.csdn.net/xudan1010/article/details/53435018
参考文章:
-
SSM框架——使用MyBatis Generator自动创建代码
2014-04-17 10:18:03这两天需要用到MyBatis的代码自动生成的功能,由于MyBatis属于一种半自动的ORM框架,所以主要的工作就是配置Mapping映射文件,但是由于手写映射文件很容易出错,所以可利用MyBatis生成器自动生成实体类、DAO接口和... -
-
SpringBoot整合MyBatis的步骤
2021-03-04 15:21:07目录MyBatis 整合包编写接口和xml编写配置文件 application.properties编写 controller 测试使用所有依赖 MyBatis 整合包 <!-- Mybatis ... -
Spring+SpringMVC+Mybatis框架整合例子(SSM) 下载
2014-07-21 12:06:07本资源对应博文:http://blog.csdn.net/zhshulin/article/details/37956105,可以通过博文进行学习,不建议下载完整源码,博文有详细教程,以及代码。 -
Mybatis关联查询之一对多和多对一XML配置详解
2017-12-21 10:53:05平时在开发过程中dao、bean和XML文件都是自动生成的,很少写XML的配置关系,今天记录一下mybatis的关联查询中的多对一和一对多的情况。 首先是有两张表(学生表Student和老师Teacher表),为了更易懂,这里只设置了... -
MyBatis快速入门第八讲——MyBatis逆向工程自动生成代码
2017-05-13 22:42:56MyBatis框架的学习(七)——MyBatis逆向工程自动生成代码什么是逆向工程MyBatis的一个主要的特点就是需要程序员自己编写sql,那么如果表太多的话,难免会很麻烦,所以mybatis官方提供了一个逆向工程,可以针对单表... -
SpringMVC+Spring+Mybatis集成开发环境
2015-04-28 11:28:08SpringMVC+Spring+Mybatis集成开发环境 -
开源框架面试之MyBatis面试题
2020-10-05 23:38:07文章目录1、什么是 MyBatis?2、讲下MyBatis的缓存3、Mybatis是如何进行分页的?分页插件的原理是什么?4、简述Mybatis的插件运行原理,以及如何编写一个插件?5、Mybatis动态sql是做什么的?都有哪些动态sql?能... -
最简单的SpringBoot整合MyBatis教程
2019-03-18 17:22:16前面两篇文章和读者聊了Spring Boot中最简单的数据持久化方案JdbcTemplate,JdbcTemplate虽然简单,但是用的并不多,因为它没有MyBatis方便,在Spring+SpringMVC中整合MyBatis步骤还是有点复杂的,要配置多个Bean,... -
Springboot集成MyBatis-Plus的使用
2020-06-15 14:11:25MyBatis-Plus介绍 Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。这是官方给的定义,关于mybatis-plus的更多介绍及特性,可以参考mybatis-... -
Spring Boot 集成MyBatis
2015-12-27 15:29:01Spring Boot 集成MyBatis在配置MyBatis前,我们先配置一个druid数据源。Spring Boot 集成druiddruid有很多个配置选项,使用Spring Boot 的ConfigurationProperties我们可以很方便的配置druid。创建DataSourceConfig... -
解决在springboot+mybatis+postgresql时,数据库字段类型为json时,如何与mybatis进行映射
2018-05-29 17:59:27pg 数据库中 某字段类型为jsonJava...在mybatis的xml中,常规无法直接进行映射,需要自己写一个TypeHandler,自定义一个JSONTypeHandlerPg类具体代码:package com.geovis.common.config; import java.sql.Callable... -
MyBatis实战教程
2019-06-28 16:00:40本课程使用Eclipse和IntelliJ IDEA两种开发工具,详细的讲解了MyBatis的各种语法,并且讲解了MyBatis逆向工程和MyBatis两种常用的插件:MyBatis Plus和通用Mapper。 本课程从理论和实际案例两方面充分讲解了MyBatis... -
mybatis预设
2019-09-03 19:31:52mapper.xml: <?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... -
mybatis mybatis plus怎么忽略映射字段
2018-11-09 21:20:04其实mybatis plus是比mybatis优秀的mybatis有的,他全有,它没的,或者不优秀的地方,mybatis plus全优秀,所以晚的总比早的好。 今天要说的是: 忽略字段问题,我被这个坑了好长时间,我开发项目呐有个需求是忽略... -
mybatis中LIKE模糊查询的几种写法以及注意点
2018-08-20 19:42:58mybatis中对于使用like来进行模糊查询的几种方式: (1)使用${...} 注意:由于$是参数直接注入的,导致这种写法,大括号里面不能注明jdbcType,不然会报错 org.mybatis.spring.MyBatisSystemException: ... -
Hibernate与 MyBatis的比较
2012-11-16 11:42:15最近做了一个Hibernate与MyBatis的对比总结,希望大家指出不对之处。 第一章 Hibernate与MyBatis Hibernate 是当前最流行的O/R mapping框架,它出身于sf.net,现在已经成为Jboss的一部分。 Mybatis 是另外一... -
TKmybatis
2020-06-19 17:52:48TKmybatis Tkmybatis是基于Mybatis框架开发的一个工具,通过调用它提供的方法实现对单表的数据操作,不需要写任何sql语句 Springboot 整合 TKmybatis 引入TkMybatis的Maven依赖 实体类的相关配置,@Id,@Table Mapper... -
Mybatis 开启控制台打印sql语句
2018-09-21 13:09:08springboot+mybatis整合过程中,开启控制台sql语句打印的两种方式: 方法一: 1.在mybatis的配置文件中添加: <settings> <!-- 打印sql日志 --> <setting name="... -
浅谈mybatis优缺点
2013-11-30 14:24:35通过上篇介绍mybatis与hibernate区别,我们已经能得出一些mybatis的优缺点,但那只是相对于hibernate的,并不全面,我来继续总结mybatis的优缺点,以便大家对于mybatis的了解能更全面些。但我所说的优缺点,仅是我... -
springBoot 使用 mybatis-plus 插件 实现分页
2018-10-30 16:32:58一、项目结构 二、pom.xml 依赖添加 (这里我是加在krystal_dao的pom.xml里面,单个项目,直接加在pom.xml,多模块根据自己项目情况添加) <dependency&...mybatis-plus</arti... -
【SSM -MyBatis篇03】MyBatis Generator(MBG)配置属性详解(基于MyBatis3) - 逆向生成 - 配置MBG模板
2020-09-26 14:11:58文章目录MyBatis Generator简介.MyBatis Generator的配置使用(基于MyBatis3) MyBatis Generator简介. MyBatis Generator(MBG)是MyBatis和iBATIS的代码生成器(逆向生成)。它将自动将查询数据库表,并将生成可... -
Mybatis 和 Mybatis Plus 的区别
2020-08-26 19:52:39Mybatis-Plus是一个Mybatis的增强工具,只是在Mybatis的基础上做了增强却不做改变,MyBatis-Plus支持所有Mybatis原生的特性,所以引入Mybatis-Plus不会对现有的Mybatis构架产生任何影响。 MyBatis的优缺点 优点 ... -
mybatis plus
2019-04-01 11:56:58mybatis的缺点: 1.mybatis sql工作量很大,尤其是字段多的时候。虽然说单表的增删改查操作可以通过mybatis generator工具来生成(或者自己写模板工具生成),但项目开发的过程中总免不了要新添加新字段,这些工具就... -
MyBatis系列 - 导读
2021-01-04 17:35:16MyBatis系列 - 导读 该系列文档是本人在学习 Mybatis 的源码过程中总结下来的,可能对各位读者会不太友好,阅读前需要对 MyBatis 和 Spring 有一定的了解。比较适合刚接触,会使用但是一直没去探究底层的同学。 ... -
使用 MyBatis 必看三篇文档导读:MyBatis、MyBatis_Generator 与 MyBatis-Spring
2015-10-06 09:39:10使用 MyBatis 必看三篇文档导读:MyBatis、MyBatis_Generator 与 MyBatis-Spring