Mybatis Plus的使用
环境搭建
pom.xml
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
| <dependencies> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.21</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.19</version> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>5.2.3.RELEASE</version> </dependency> </dependencies>
|
spring.xml
在这里注入的sqlSessionFactoryBean
需要使用Mybatis Plus
的com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean
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
| <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd">
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${driverClassName}"></property> <property name="url" value="${url}"></property> <property name="username" value="${username}"></property> <property name="password" value="${password}"></property> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="sqlSessionFactoryBean" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.mashibing.dao"></property> </bean> </beans>
|
EmpDao.java
通过继承Mybatis Plus
提供的BaseMapper
来实现接口映射,默认会提供多种API接口调用,不需要再编写EmpDao.xml
1 2 3
| public interface EmpDao extends BaseMapper<Emp> { public List<Emp> selectEmpByCondition(); }
|
Test.java
1 2 3 4 5 6 7 8
| public class Test { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
@Test public void test02(){ EmpDao empDao = context.getBean("empDao", EmpDao.class); } }
|
增删改查
插入操作
1 2 3 4 5 6 7 8 9 10 11 12 13
|
@Test public void testInsert(){ Emp emp = new Emp(); emp.seteName("zhangsan"); emp.setJob("Teacher"); emp.setDeptno(10); int insert = empDao.insert(emp); System.out.println(insert); }
|
当运行上述代码的时候,发现报错了,原因在于你写的实体类的名称跟表的名称不匹配,因此在实现的是需要添加@TableName
注解,指定具体的表的名称。
运行通过之后,大家会发现结果能够正常的进行插入,但是在控制台会打印一个警告信息,说没有@TableId的注解,原因就在于定义实体类的时候并没有声明其中的主键是哪个列,以及使用什么样的主键生成策略,因此,可以在类的属性上添加如下注解,来消除此警告。
1 2 3 4 5 6 7 8 9 10
| @TableName("tbl_emp") public class Emp {
@TableId(value = "empno",type = IdType.AUTO) private Integer empno; }
|
MyBatis plus
在插入操作的过程中,会动态调整SQL语句,根据输入的对象的字段的个数来动态的调整SQL语句插入的字段。
修改操作
1 2 3 4 5 6
| Emp emp = new Emp(); emp.setEmpno(6); emp.seteName("lisi"); emp.setJob("Teacher"); emp.setMgr(100); int insert = empDao.updateById(emp);
|
删除操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| int i = empDao.deleteById(6);
int i = empDao.deleteBatchIds(Arrays.asList(1, 2, 3));
Map<String,Object> map = new HashMap<String,Object>(); map.put("empno",4); int i = empDao.deleteByMap(map);
QueryWrapper wrapper = new QueryWrapper(); wrapper.eq("empno",7); int delete = empDao.delete(wrapper);
|
查询操作
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
|
QueryWrapper wrapper = new QueryWrapper(); wrapper.eq("empno","8"); wrapper.eq("e_name","zhangsan"); Emp emp = empdao.selectOne(wrapper);
List<Emp> list = empdao.selectList(null); System.out.println(list);
List<Emp> list = empdao.selectBatchIds(Arrays.asList(8, 9)); System.out.println(list);
Emp emp = empdao.selectById(8);
List<Map<String, Object>> maps = empdao.selectMaps(null);
Integer integer = empdao.selectCount(null); System.out.println(integer);
|
分页操作
1 2 3 4 5 6 7 8 9 10 11
| <plugins> <plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"></plugin> </plugins>
<property name="plugins"> <array> <bean class="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"></bean> </array> </property>
|
1 2
| Page<Emp> empPage = empDao.selectPage(new Page<>(2, 5), null); List<Emp> records = empPage.getRecords();
|
相关配置
官网
在此链接中包含了非常多的配置项,用户可以按照自己的需求添加需要的配置,配置方式如下:
spring.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"> <property name="configuration" ref="configuration"/> <property name="globalConfig" ref="globalConfig"/> ...... </bean>
<bean id="configuration" class="com.baomidou.mybatisplus.core.MybatisConfiguration"> ...... </bean>
<bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig"> <property name="dbConfig" ref="dbConfig"/> ...... </bean>
<bean id="dbConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig.DbConfig"> ...... </bean>
|
通过这个配置文件的配置,大家可以进行回想上述问题的出现,mybatis-plus是如何解决这个问题的呢?
在mybatis-plus中会引入写默认的配置,这个选项的默认配置为true,因此可以完成对应的实现。
我们可以通过如下配置来禁用驼峰标识的操作,如下所示:
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
| <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <context:property-placeholder location="classpath:db.properties"></context:property-placeholder> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${driverClassname}"></property> <property name="url" value="${url}"></property> <property name="username" value="${username}"></property> <property name="password" value="${password}"></property> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean>
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven> <bean id="sqlSessionFactoryBean" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <property name="dataSource" ref="dataSource"></property> <property name="typeAliasesPackage" value="com.mashibing.bean"></property> <property name="globalConfig" ref="globalConfig"></property> <property name="configuration" ref="configuration"></property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.mashibing.dao"></property> </bean> <bean id="configuration" class="com.baomidou.mybatisplus.core.MybatisConfiguration"> <property name="mapUnderscoreToCamelCase" value="false"></property> </bean>
<bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig"> <property name="dbConfig" ref="dbConfig"></property> </bean> <bean id="dbConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig.DbConfig"> </bean> </beans>
|
1、当添加上述配置之后,大家发现运行过程中报错,
Property ‘configuration’ and ‘configLocation’ can not specified with together
表示这两个标签无法同时使用,因此我们可以选择将configLocation给禁用掉,就是不使用mybatis的配置,此时就能够正常使用了,但是放置属性的时候又报错了,原因就在于我们把驼峰标识给禁用了,重新开启即可。除此之外,我们还可以在属性的上面添加@TableField属性
1 2
| @TableField(value = "e_name") private String eName;
|
2、此时发现日志功能又无法使用了,只需要添加如下配置即可
1 2 3 4
| <bean id="configuration" class="com.baomidou.mybatisplus.core.MybatisConfiguration"> <property name="mapUnderscoreToCamelCase" value="true"></property> <property name="logImpl" value="org.apache.ibatis.logging.log4j.Log4jImpl"></property> </bean>
|
3、我们在刚刚插入数据的时候发现每个类可能都需要写主键生成策略,这是比较麻烦的,因此可以选择将主键配置策略设置到全局配置中。
1 2 3 4
| <bean id="dbConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig.DbConfig"> <property name="idType" ref="idType"></property> </bean> <util:constant id="idType" static-field="com.baomidou.mybatisplus.annotation.IdType.AUTO"></util:constant>
|
4、如果你的表的名字都具备相同的前缀,那么可以设置默认的前缀配置策略,此时的话可以将实体类上的@TableName标签省略不写
1 2 3 4 5
| <bean id="dbConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig.DbConfig"> <property name="idType" ref="idType"></property> <property name="tablePrefix" value="tbl_"></property> </bean> <util:constant id="idType" static-field="com.baomidou.mybatisplus.annotation.IdType.AUTO"></util:constant>
|
5、在mybatis-plus中如果需要获取插入的数据的主键的值,那么直接获取即可,原因就在于配置文件中指定了默认的属性为true
代码生成器
1 2 3 4 5
| <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.3.1.tmp</version> </dependency>
|
添加 模板引擎 依赖,MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引擎,如果都不满足您的要求,可以采用自定义模板引擎。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.30</version> </dependency> <dependency> <groupId>com.ibeetl</groupId> <artifactId>beetl</artifactId> <version>3.1.1.RELEASE</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
| import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.generator.AutoGenerator; 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.NamingStrategy; import org.junit.Test;
public class MyTest {
@Test public void testGenerator(){ GlobalConfig globalConfig = new GlobalConfig(); globalConfig.setActiveRecord(true) .setAuthor("lian") .setOutputDir("e:\\self_project\\mybatisplus_generatorcode\\src\\main\\java") .setFileOverride(true) .setIdType(IdType.AUTO) .setServiceName("%sService") .setBaseResultMap(true) .setBaseColumnList(true);
DataSourceConfig dataSourceConfig = new DataSourceConfig(); dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver") .setUrl("jdbc:mysql://192.168.85.111:3306/mp?serverTimezone=UTC") .setUsername("root").setPassword("123456");
StrategyConfig strategyConfig = new StrategyConfig(); strategyConfig.setCapitalMode(true) .setNaming(NamingStrategy.underline_to_camel) .setTablePrefix("tbl_") .setInclude("tbl_emp");
PackageConfig packageConfig = new PackageConfig(); packageConfig.setParent("com.mashibing") .setMapper("mapper") .setService("service") .setController("controller") .setEntity("bean") .setXml("mapper");
AutoGenerator autoGenerator = new AutoGenerator(); autoGenerator.setGlobalConfig(globalConfig).setDataSource(dataSourceConfig).setStrategy(strategyConfig) .setPackageInfo(packageConfig);
autoGenerator.execute(); } }
|
乐观锁插件
当要更新一条记录的时候,希望这条记录没有被别人更新,通过比列中的版本字段来判断是否更新,需要对该字段添加@Version
注解
取出记录时,获取当前version,更新时,带上这个version,执行更新时, set version = newVersion where version = oldVersion,如果version不对,就更新失败
添加配置:
1
| <bean class="com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor"></bean>
|
1 2
| <bean class="com.baomidou.mybatisplus.extension.plugins.IllegalSQLInterceptor"> </bean>
|
1 2 3 4 5 6 7 8 9
| @Test public void testSqlIllegal(){ QueryWrapper<Emp> queryWrapper = new QueryWrapper<>(); queryWrapper.or(); List<Emp> list = empDao.selectList(queryWrapper); for (Emp emp : list) { System.out.println(emp); } }
|