05、MyBatisPlus
1、 MyBatis Plus 的简介
1.1、为什么使用MyBatis Plus?
再之前学习的Mybatis中 我们对单表的增删改查的操作,都是自己在mapper.xml中进行代码的书写,这样一来我们书写的代码比较的麻烦。
我们目前封装数据库的实体的时候,每一表都需要自己的书写实体类,这样一来,我们书写的代码就比较的麻烦。
1.2、解决的方案
MyBatis Plus:其实就是对MyBatis的进一步的封装
1.3、MyBatisPlus简介

Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
官方文档说的愿景是成为 Mybatis 最好的搭档,就像魂斗罗中的1P、2P,基友搭配,效率翻倍。
1.4、特性

1.5、架构原理

2、MyBatis Plus 的框架搭建
2.1、导包
在原有SSM的jar包的基础上增加MybatisPlus的jar即可。

2.2、搭建SSM开发环境
1、在Src下创建MVC的包结构
2、在src下创建和配置SSM相关配置文件
注意:
其他配置和原有SSM流程不变,在applicationcontext.xml文件中
将Mybatis的工厂bean替换为MybatisPlus的工厂bean即可。
2.1、springmvc.xml
<!--配置注解扫描--> <context:component-scan base-package="com.bjsxt.controller"></context:component-scan> <!--配置注解解析器--> <mvc:annotation-driven></mvc:annotation-driven> <!--配置静态资源放行--> <mvc:resources mapping="/js/**" location="/js/"></mvc:resources> <mvc:resources mapping="/css/**" location="/css/"></mvc:resources> <mvc:resources mapping="/images/**" location="/images/"></mvc:resources>
2.2、applicationcontext.xml
<!--属性文件扫描--> <context:property-placeholder location="classpath:db.properties"></context:property-placeholder> <!--配置注解扫描--> <context:component-scan base-package="com.bjsxt.service.impl"></context:component-scan> <!--配置数据源bean--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${mysql.driver}"></property> <property name="url" value="${mysql.url}"></property> <property name="username" value="${mysql.username}"></property> <property name="password" value="${mysql.password}"></property> </bean> <!--配置工厂bean--> <bean id="factory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"> <!--配置全局策略--> <property name="globalConfig" ref="globalConfig"></property> <!--配置mp的分页插件--> <property name="plugins"> <array> <!--配置分页插件:拦截对象--> <bean class="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"> <property name="dialectType" value="mysql"></property><!--指明要进行分页操作的数据库--> </bean> </array> </property> </bean> <!--配置mp的全局策略--> <bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig"> <!--配置数据库全局默认的映射关系--> <property name="dbConfig"> <bean id="dbConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig"> <!--声明全局默认类名的对应的表的前缀--> <property name="tablePrefix" value="t_"></property> <!--配置全局主键自增--> <property name="idType" value="AUTO"></property> </bean> </property> </bean> <!--配置Mapper扫描bean--> <bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="factory"></property> <property name="basePackage" value="com.bjsxt.mapper"></property> </bean> <!--配置事务管理bean--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"></bean> <!--配置事务管理方法--> <tx:advice id="advice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="sel*" read-only="true"/> <tx:method name="ins*"/> <tx:method name="up*"/> <tx:method name="del*"/> </tx:attributes> </tx:advice> <!--配置事务管理切面--> <aop:config> <aop:pointcut id="mp" expression="execution(* com.bjsxt.service.impl.*.*(..))"/> <aop:advisor advice-ref="advice" pointcut-ref="mp"></aop:advisor> </aop:config>
2.3、db.properties
mysql.driver=com.mysql.jdbc.Driver mysql.url=jdbc:mysql://localhost:3306/mp mysql.username=root mysql.password=1234
2.4、log4j.properties
log4j.rootCategory=info log4j.logger.com.bjsxt.mapper=debug, CONSOLE,LOGFILE log4j.logger.com.bjsxt.advice=debug, CONSOLE,LOGFILE log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=- %c-%d-%m%n log4j.appender.LOGFILE=org.apache.log4j.FileAppender log4j.appender.LOGFILE.File=D:/axis.log log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=- %c-%d-%m%n
3、在web.xml中配置SSM相关信息
<!--配置Spring容器的配置文件路径--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationcontext.xml</param-value> </context-param> <!--配置Spring的监听器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--配置SpringMVC的Servlet--> <servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--配置编码过滤器--> <filter> <filter-name>code</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>code</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2.3、创建测试表
创建t_student表并添加测试数据

2.4、实体类
//@TableName("t_student") public class Student { @TableId(type = IdType.AUTO) private Integer sid; @TableField("s_name") private String sname; private Integer sage; private String ssex; private String sphone; @TableField(exist = false) private String fav; ........ }
2.5、继承BaseMapper接口
public interface StudentMapper extends BaseMapper<Student> { }
2.6、测试
/** * 测试使用mp查询所有的学生信息 */ @Test public void testSelAllStu(){ //获取Spring容器对象 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationcontext.xml"); //获取StudentMapper接口的实例化对象 StudentMapper studentMapper= (StudentMapper) ac.getBean("studentMapper"); //查询所有的学生信息 List<Student> students = studentMapper.selectList(null); //输出结果 System.out.println(students); }
2.7、MyBatis和Mybatis Plus的使用比较
MybatisPlus包含了Mybatis的所有功能,也就说在MybatisPlus中我们仍然可以按照Mybatis的方式来完成数据库的操作(无侵入)。
MybatisPlus的数据库操作的Mapper层的接口只需要继承BaseMapper接口,就自动的拥有了当前对应的表的基本的CRUE操作,无需声明接口方法及其xml文件,极大的提升了开发效率(MybatisPlus是通过实体类来逆向动态生成对应的表的基本的Sql语句)
3、MyBatisPlus中的CRUD
3.1、添加操作
/** * MP的新增 * insert方法: * 说明:BaseMapper接口中提供了数据新增的insert方法 * 作用:完成数据的新增 * 参数:封装了要新增的数据的实体类对象 * 使用: * 直接调用即可。但是在进行根据实体类动态生成SqL语句时 * 会判断实体类中的属性值是否为nuLl,只有非nuLl值才会拼接在SqL语句中完成新增 * 注意: * 需要在实体类中使用注解@TabLeName指明实体类对应的表名,如果类名和表名一致则省略不写 * 需要在对应主键的属性上使用注解@TableId表明该属性是表的主键,并且需要说主键的设置类型, * 比如:自增需要在普通属性上使用注解(@TableField表明该属性对应的字段的名称,如果属性名和字段名一致,则省略不写 */ @Test public void testIns(){ //获取Spring容器对象 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationcontext.xml"); //获取StudentMapper接口的实例化对象 StudentMapper studentMapper= (StudentMapper) ac.getBean("studentMapper"); //创建学生对象存储要新增的学生信息 Student student=new Student(); student.setSname("赵六"); student.setSage(40); student.setSsex("1"); student.setSphone("19988665533"); //新增学生信息 int i = studentMapper.insert(student); //输出新增结果 System.out.println("新增学生信息:"+i+":"+student); }
3.2、修改操作
/** * updateById方法 * 作用:更新数据到数据库中 * 参数:存储了要更新的数据的值 * 注意: * 根据主铤ID作为条件来完成更新,并且只更新实体类中 * 有值的属性,nuLL值的属性不参与更新 */ @Test public void testUp(){ //获取Spring容器对象 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationcontext.xml"); //获取StudentMapper接口的实例化对象 StudentMapper studentMapper= (StudentMapper) ac.getBean("studentMapper"); //创建学生对象存储要修改的信息以及要修改的学生的ID Student student=new Student(); student.setSid(6); student.setSname("赵六六"); //修改学生信息 int i = studentMapper.updateById(student); //输出结果 System.out.println("修改学生信息:"+i); }
3.3、删除操作
/** * 删除:通过ID删除 */ @Test public void testDelById(){ //获取Spring容器对象 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationcontext.xml"); //获取StudentMapper接口的实例化对象 StudentMapper studentMapper= (StudentMapper) ac.getBean("studentMapper"); //根据ID删除学生信息 int i = studentMapper.deleteById(6); //输出结果 System.out.println("根据ID删除结果:"+i); } /** * 删除:指定条件删除数据,deleteByMap * 作用:根据指定的字段完成数据的删除 * 参数: map集合 * 注意: * 传入的map集合中存储了要删除的数据的键值对, * 键名为数据库中的字段的名称,不是实体类的属性名。 */ @Test public void testDelByMap(){ //获取Spring容器对象 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationcontext.xml"); //获取StudentMapper接口的实例化对象 StudentMapper studentMapper= (StudentMapper) ac.getBean("studentMapper"); //创建map集合存储删除条件 Map<String,Object> map=new HashMap<>(); map.put("s_name","赵六"); map.put("sage",40); //根据指定的条件删除学生信息 int i = studentMapper.deleteByMap(map); //输出结果 System.out.println("根据条件删除结果:"+i); } /** * 删除:多选删除 * 作用:多选删除,将符合ID要求的数据全部删除 * 参数:存储了要删除的数据的ID的集合 */ @Test public void testDelByIds(){ //获取Spring容器对象 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationcontext.xml"); //获取StudentMapper接口的实例化对象 StudentMapper studentMapper= (StudentMapper) ac.getBean("studentMapper"); //创建List集合存储要删除的数据的Id List<Integer> list=new ArrayList<>(); list.add(2); list.add(3); //删除符合Id要求的数据 int i = studentMapper.deleteBatchIds(list); //输出结果 System.out.println("多选删除结果:"+i); }
3.4、查询操作
/** * 查询:通过ID查询 * 参数:要查询的数据的ID * 返回值:存储了查询结果的实体类对象 */ @Test public void testselById(){ //获取Spring容器对象 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationcontext.xml"); //获取StudentMapper接口的实例化对象 StudentMapper studentMapper= (StudentMapper) ac.getBean("studentMapper"); //根据ID查询 Student student = studentMapper.selectById(1); //输出结果 System.out.println("查询结果:"+student); } /** * 作用:根据指定的字段查询数据 * 参数:存储了指定字段及其字段值的map集合 * 返回值:存储了查询结果的List集合 * 注意: * map中的键名为要查询的数据的字段名,不是实体类的属性名 */ @Test public void testselByMap(){ //获取Spring容器对象 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationcontext.xml"); //获取StudentMapper接口的实例化对象 StudentMapper studentMapper= (StudentMapper) ac.getBean("studentMapper"); //创建Map集合存储查询条件 Map<String,Object> map=new HashMap<>(); map.put("s_name","张三"); map.put("sage",20); //根据指定的条件查询 List<Student> students = studentMapper.selectByMap(map); //输出结果 System.out.println("查修结果:"+students); } /** * 作用:根据id查询数据 * 参数:存储了要查询的数据的Id的集合 * 返回值:存储了查询结果的List集合 */ @Test public void testselByIds(){ //获取Spring容器对象 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationcontext.xml"); //获取StudentMapper接口的实例化对象 StudentMapper studentMapper= (StudentMapper) ac.getBean("studentMapper"); //创建List集合存储id数据 List<Integer> list=new ArrayList<>(); list.add(1); list.add(2); //根据Id的集合查询信息 List<Student> students = studentMapper.selectBatchIds(list); //输出结果 System.out.println("查询结果:"+students); }
4、条件构造器Wrapper
4.1、Wrapper条件构造器的介绍
1、问题:
目前我们可以使用mp完成基本的增删改查操作,但是我们在进行数据操作时,很多时候Sql语句中的筛选条件是非常复杂的,比如or关键,>,<,模糊查询等,怎么办?
2、解决:
mp提供了功能非常强大的Wrapper条件构造器
3、本质:
条件构造器其实就是一个对象,以方法的形式提供了数据库操作的筛选关键字我们调用该对象,来拼接我们的筛选条件即可。
4、实现:
QueryWrapper
5、使用:
创建QueryWrapper对象,使用该对象中提供的对应的数据库操作的方法,来完成条件的拼接,QueryWrapper对象最终存储拼接好的Sql片段,将片段拼接在Sql语句中。
4.3、常用的方法说明

4.4、带条件的查询的代码示例
/** * * 查询: * 使用条件构造器封装查询条件 * 条件构造器是以java对象的形式将数据操作的筛选条件描述出来,然后由mp * 将其翻译成对应的sql判断拼接在sql语句上。 */ @Test public void selMpWrapper(){ //获取Spring容器对象 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationcontext.xml"); //获取mapper对象 StudentMapper studentMapper= (StudentMapper) ac.getBean("studentMapper"); //创建条件构造器对象 QueryWrapper<Student> queryWrapper=new QueryWrapper<>(); queryWrapper.eq("sage", 20).or().like("s_name","张"); /*queryWrapper.or(); queryWrapper.eq("s_name","张三");*/ //根据条件查询数据 List<Student> students = studentMapper.selectList(queryWrapper); //输出结果 System.out.println("查询结果:"+students); }
5、MybatisPlus的分页查询
5.1、分页查询介绍
1、问题:
对于传统的分页Sql语句,需要我们自己在Sql语句中使用limit关键字来实现分页查询。但是呢,在MybatisPlus中,Sql语句是动态生成的,那么如何完成数据的分页查询呢?
2、解决:
使用分页插件。
3、使用:
在配置文件中配置分页插件
在代码中调用分页效果
5.2、分页查询的配置
<!--配置工厂bean--> <bean id="factory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"> <!--配置全局策略--> <property name="globalConfig" ref="globalConfig"></property> <!--配置mp的分页插件--> <property name="plugins"> <array> <!--配置分页插件:拦截对象--> <bean class="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"> <property name="dialectType" value="mysql"></property><!--指明要进行分页操作的数据库--> </bean> </array> </property> </bean>
5.3、分页查询的使用
/** * 1、创建page对象,在该对象中声明页码数和每页的数量 * 2、调用seLectPage方法完成分页查询 * 参数: * Page参数:封装了分页的页码数和每页数量的对象 * wrapper参数: * 封装了筛选条件的条件构造器对象。 * 没有筛选条件则传入nuLL值 * 3、从seLectPage方法的返回值对象Page中获取分页数据 */ @Test public void testMpPage() { //获取Spring容器对象 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationcontext.xml"); //获取mapper对象 StudentMapper studentMapper = (StudentMapper) ac.getBean("studentMapper"); //创建Page对象封装分页查询条件 IPage<Student> page = new Page<>(1, 2); //查询 IPage<Student> studentIPage = studentMapper.selectPage(page, null); //输出结果 System.out.println("分页查询结果:" + studentIPage.getRecords()); System.out.println("分页总共的数据量:" + studentIPage.getTotal()); System.out.println("分页总共的页码数:" + studentIPage.getPages()); //分页查询名字中包含"同学"的数据 //创建分页对象 Page<Student> p = new Page<>(1, 2);//分页查询 Page<Student> p2 = studentMapper.selectPage(p, new QueryWrapper<Student>() .like("s_name", "同学") .eq("sage", 20)); //输出分页查询结果 System.out.println("获取当前的分页数据:"+p2.getRecords()); System.out.println("获取当前的页码数: "+p2.getCurrent()); System.out.println("获取当前的每页显示的数据量: "+p2.getSize()); System.out.println("总的数据量: "+p2.getTotal()); System.out.println("总的页码数: "+p2.getPages()); }
6、常用注解
6.1、注解的介绍
1、问题:
在使用MybatisPlus后,我们不用再声明Sql语句了,只需要我们的Mapper接口继承BaseMapper接口即可拥有对应的CRUD操作。通过我们之前的学习我们发现,MyBatisPlus其实在根据我们的实体类来动态的生成对象的Sql语句默认会按照类名即是对应的表的表名,属性名即是对应的表的字段名。但是如果实体类名和表名不一致,或者属性名和字段名不一致怎么办?
2、解决:
在实体类上使用注解表名对应的映射关系。
3、注意:
建议大家在开发时尽量保证实体类和表之间的对应关系是相同的。这样就不用声明注解。
6.2、常用注解及其作用
1、@TableName注解
作用:
表明实体类对应的数据库表
使用:
在类名上使用,值为对应的表的表名
//@TableName("t_student") public class Student { }
官方说明:

2、@TableId
作用:
表明类中的某个属性为主键字段对应的属性
使用:
在为主键的属性上使用
示例:
@TableId(type = IdType.AUTO) private Integer sid;
官方说明:

3、@TableField
作用:
表明普通属性映射的表中的字段,值为字段名
使用:
在普通属性上使用
示例:
@TableField("s_name")
private String sname;
@TableField(exist = false)
private String fav;
官方说明:

6.3、获取自增的主键值
在Mybatis中需要使用 useGeneratedKeys,keyProperty,keyColumn 设置自增主键值的回返,在实体类对象中获取即可。
在MybatisPlus中在进行数据新增时,在新增成功后,会自动的将自增的主键值返回到实体类对象中,前提是需要在实体类中使用@TableId表明主键字段,并且为自增类型。
7、全局配置策略
7.1、全局配置策略介绍
假如我们每个实体类和数据库中的表名都不一致,表的格式都是t_表名,类名呢没有t_字符,比如t_student表和Student类。
这样每个实体类上我们都要使用@TableName注解来表名类和表的映射关系,过于麻烦怎么办?
解决:
使用MP的全局配置策略。GlobalConfig
作用:
配置表和类名映射关系的前缀。
配置全局主键自增
7.2、全局配置策略示例
<!--配置工厂bean--> <bean id="factory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean"> <!--配置全局策略--> <property name="globalConfig" ref="globalConfig"></property> <!--配置mp的分页插件--> <property name="plugins"> <array> <!--配置分页插件:拦截对象--> <bean class="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"> <property name="dialectType" value="mysql"></property><!--指明要进行分页操作的数据库--> </bean> </array> </property> </bean> <!--配置mp的全局策略--> <bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig"> <!--配置数据库全局默认的映射关系--> <property name="dbConfig"> <bean id="dbConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig"> <!--声明全局默认类名的对应的表的前缀--> <property name="tablePrefix" value="t_"></property> <!--配置全局主键自增--> <property name="idType" value="AUTO"></property> </bean> </property> </bean>
8、Active Record
支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
8.1、AR模式和MP的Mapper模式的比较
1、原有MP的Mapper模式
① 创建项目完成Spring和MP的集成
② 创建数据库表对应的实体类
③ 创建mapper接口并继承BaseMapper接口
④ 从Spring容器中获取Mapper接口的实例化对象完成数据库操作
描述:
通过以上流程,MP的操作模式较于原有Mybatis的数据库操作流程没有任何变化,只是我们在编写代码的时候不用在mapper层声明Sql语句或者XML文件了,提升开发效率。
2、MP的AR模式
① 创建项目完成Spring和MP的集成
② 创建数据库表对应的实体类,继续Model类
③ 在实体类中覆写pkVal方法.
④ 创建Mapper接口并继承BaseMapper接口
⑤ 创建Spring对象,让Spring容器完成对Mapper层的实例化扫描
⑥ 创建实体类对象,直接调用实体类从Model中继承的数据库方法完成数据库操作。
3、流程比较分析
MP的AR模式其实底层仍然使用的是Mapper层在完成数据库操作。只不过由我们自己调用Mappe对象操作数据库,变成了通过实体类对象来调用Mapper完成数据库操作。从代码的物理视图上我们是看不到实体类调用Mapper的过程的。也就说,本质上仍然是Mapper层在操作数据库
8.2、AR模式的特点
AR模式较于传统的MP模式操作数据库,在代码体系中,我们不用再获取Mapper对象,然后再将实体类传入给mapper层完成数据库操作,直接使用实体类即可完成操作。提升开发效率。
8.3、AR模式的使用代码示例
创建一个集成了MP的SSM项目
在pojo层创建实体类,并继承Model类,覆写pkVal的方法
import com.baomidou.mybatisplus.extension.activerecord.Model;
public class Student extends Model { @TableId private Integer sid; @TableField("s_name") private String sname; private Integer sage; private String ssex; private String sphone; //复写pkVal方法 @Override protected Serializable pkVal() { return sid; } }
1、查询
/** * 测试Mp的AR模式的查询 */ @Test public void testAr(){ //获取Spring容器对象 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationcontext.xml"); //获取Student的实体类对象 Student student=new Student(); //使用AR模式操作数据库 //AR的查询的查询所有 List list = student.selectAll(); //输出查询结果 System.out.println("AR模式的查询:"+list); //AR模式的根据ID查询 student.setSid(1); Student stu = (Student) student.selectById(); System.out.println("根据Id查询的结果:"+stu); }
2、新增
/** * 测试Mp的AR模式的新增 */ @Test public void testArAdd(){ //获取Spring容器对象 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationcontext.xml"); //获取Student的实体类对象 Student student=new Student(); student.setSname("小特"); student.setSage(70); student.setSsex("1"); student.setSphone("4564654"); //使用AR模式的新增 boolean insert = student.insert(); System.out.println("新增结果:"+insert); }
3、更新
/** * 测试Mp的AR模式的更新 */ @Test public void testArUp(){ //获取Spring容器对象 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationcontext.xml"); //获取Student的实体类对象 Student student=new Student(); student.setSid(1); student.setSname("张三三"); //AR的更新 boolean b = student.updateById(); System.out.println("更新结果:"+b); }
4、删除
/** * 测试Mp的AR模式的删除 */ @Test public void testArDel(){ //获取Spring容器对象 ApplicationContext ac=new ClassPathXmlApplicationContext("applicationcontext.xml"); //获取Student的实体类对象 Student student=new Student(); student.setSid(10); //AR的删除 boolean b = student.deleteById(); System.out.println("删除结果:"+b); }
9、代码生成器
9.1、代码生成器介绍
问题:
目前我们在开发SSM项目的时候,会先搭建一个SSM的开发环境。我们会根据数据库的表在pojo包中创建对应的实体类,而且可以不关心项目功能的同时,在mapper层对数据库的表的基础增删改查功能提前实现,同理,在service层可以将基础的业务代码提前声明。然后再根据项目功能完成对应的复杂操作。而整个过程需要程序员手动完成搭建,效率低下。
解决:
创建一个代码生成类,调用该类的对象,并将对应的数据库表作为参数传递进入以及一些生成代码的其他要求也传递给该对象,让该对象帮助我们生成基础的开发代码。
实现:
MP的代码生成器
作用:
根据数据库中的表动态的生成表对应的mapper,service,pojo,controller层的基础代码,提升开发效率。
9.2、生成器的使用
1、导入代码生成器相关jar包

2、使用代码生成器生成代码
public class TestCode { public static void main(String[] args) { // 代码生成器 AutoGenerator mpg = new AutoGenerator(); //全局配置策略 GlobalConfig gc = new GlobalConfig(); String path = System.getProperty("user.dir");//动态获取当前项目的路径 System.out.println(path); gc.setFileOverride(false);// 是否覆盖同名文件,默认是false gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false gc.setEnableCache(false);// XML 二级缓存 gc.setBaseResultMap(true);// XML ResultMap gc.setBaseColumnList(false);// XML columList gc.setOutputDir(path+"/03_mp_code/src"); gc.setIdType(IdType.AUTO);//设置主键策略 //数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/mp?useUnicode=true&useSSL=false&characterEncoding=utf8"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("1234"); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent("com.bjsxt") .setMapper("mapper") .setService("service") .setController("controller") .setEntity("pojo") .setXml("mapper"); //策略配置 StrategyConfig stConfig = new StrategyConfig(); stConfig.setCapitalMode(true) //全局大写命名 .setNaming(NamingStrategy.underline_to_camel) // 数据库表映射到实体的命名策略 .setTablePrefix("t_") .setInclude("t_student"); // 生成的表,多个表继续传递即可,String类型的可变参数 //将策略配置对象集成到代码生成器中 mpg.setGlobalConfig(gc); mpg.setDataSource(dsc); mpg.setPackageInfo(pc); mpg.setStrategy(stConfig); //执行生成 mpg.execute(); } }
10、Lombok的使用
10.1、什么是LomBok
lombok是一个可以通过简单的注解的形式来帮助我们简化消除一些必须有但显得很臃肿的 Java 代码的工具,简单来说,比如我们新建了一个类,然后在其中写了几个属性,然后通常情况下我们需要手动去建立getter和setter方法啊,构造函数啊之类的,lombok的作用就是为了省去我们手动创建这些代码的麻烦,它能够在我们编译源码的时候自动帮我们生成这些方法
10.2、LomBok 的安装
首先我们需要安装IntelliJ IDEA中的lombok插件,打开IntelliJ IDEA后点击菜单栏中的File-->Settings,或者使用快捷键Ctrl+Alt+S进入到设置页面。

我们点击设置中的Plugins进行插件的安装,在右侧选择Browse repositories...,然后在搜索页面输入lombok变可以查询到下方的Lombok Plugin,鼠标点击Lombok Plugin可在右侧看到Install按钮,点击该按钮便可安装

我们在安装页面可以看到lombok具体支持的所有注解,在安装过程中有Downloading Plugins的提示,安装过程中进度条会变化。需要提醒的是,在安装过程中一定要保证网络连接可用且良好,否则可能会安装失败。安装成功后我们可以看到右侧的Restart按钮,此时可先不操作,因为我们还有后续的配置工作。安装完成后我们再回到Plugins,此时在右侧可以搜索到lombok,而安装前是不行的。

同样我们在Settings设置页面,我们点击Build,Execution,Deployment-->选择Compiler-->选中Annotation Processors,然后在右侧勾选Enable annotation processing即可

10.3、LomBok 的常用注解及使用

代码示例:
注意:在idea安装了lombok插件后 ,还需在项目中导入lombok的jar包
实体类创建示例:
@NoArgsConstructor @AllArgsConstructor @Data public class Student { private Integer sid; private String sname; private String fav; }
调用示例
public class TestStudent { public static void main(String[] args) { Student student=new Student(); student.setSid(1); student.setSname("张三"); student.setFav("唱歌"); System.out.println(student); } }
11、MyBatis X的使用
11.1、简介使用
MybatisX 是一款基于 IDEA 的快速开发插件,为效率而生。安装方法:打开 IDEA,进入 File -> Settings -> Plugins -> Browse Repositories,输入 mybatisx 搜索并安装。
11.2、功能特点
1、Java 与 XML 调回跳转
2、Mapper 方法自动生成 XML

浙公网安备 33010602011771号