首页 > 编程语言 > MybatisPlus,无XML分分钟实现CRUD操作
2020
10-09

MybatisPlus,无XML分分钟实现CRUD操作

不讲太多理论知识,官网都有,直接上手。

1.测试表

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
 `id` bigint(20) UNSIGNED NOT NULL,
 `name` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户名',
 `password` varchar(18) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '密码',
 `age` int(4) DEFAULT NULL COMMENT '年龄',
 `create_time` datetime(0) DEFAULT NULL COMMENT '创建时间',
 `update_time` datetime(0) DEFAULT NULL COMMENT '更新时间',
 PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

引入依赖

<!--mybatis-plus核心包-->
<dependency>
 <groupId>com.baomidou</groupId>
 <artifactId>mybatis-plus-boot-starter</artifactId>
 <version>3.0.5</version>
</dependency>
<!--mysql-->
<dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
</dependency>

配置文件,这里我用的是boot项目

spring:
 datasource:
 username: cjx
 password: cjx19950616
 url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
 driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
 mapper-locations: classpath:/mapper/*.xml
 #configuration:
 #map-underscore-to-camel-case: true

其实简单的crud甚至不需要mybatis-plus的配置,我这里没删除,本文也并没有用到配置文件。

实体类

 public class User{
  private Long id;
  private String name;
  private String password;
  private int age;
  private Date createTime;
  private Date updateTime;

 ...
  getter && setter
  ...
  toString()
 }

分页插件

@Configuration
public class MyBtaisPlusConfig {
 /**
  * 分页插件
  * @return
  */
 @Bean
 public PaginationInterceptor paginationInterceptor() {
  System.out.println("加载分页插件");

  return new PaginationInterceptor();
 }
}

编写一个我们的接口

@Component
public interface UserDao extends BaseMapper<User> {
 Integer deleteById(Long id);
}

接下来就可以愉快的测试了,在我们的测试类里先注入dao

@Autowired

private UserDao userMapper;

新增测试

/**
 * 新增
 */
@Test
void save(){

 User u = new User();
 u.setAge(100);
 u.setName("测试数据3");
 u.setPassword("cjx1111");
 u.setAge(25);
 int row = userMapper.insert(u);
 System.out.println(row);
}

是不是很简单?只需要这样就可以完成新增了,既然有单个插入,那少不了也有批量插入

批量新增测试

/**
 * 批量插入
 */
@Test
void save(){
 List<User> us = new LinkedList<User>();
  for (int i = 0;i < 50;i++){
   User u = new User();
   u.setName("测试数据"+i);
   u.setAge((int)(Math.random()*90+10));
   u.setPassword("mima"+i);
   us.add(u);
  }
  userService.saveBatch(us);
}

其中用到了userService,我这里贴一下代码,需要我们接口继承Iservice,实现类继承ServiceImple<M,T>,这样就可以直接调用mybatis-plus为我们提供的现成方法了。

public interface IUserService extends IService<User> {

}

实现类

@Service public class UserServiceImpl extends ServiceImpl<UserDao, User>implements IUserService {

}

修改

/**
 * 修改
 */
@Test
void updateById(){

 User u = new User();
 //修改name
 u.setId(1L);
 u.setName("修改下数据--");
 u.setPassword("123");
 u.setAge(99);
 int row = userMapper.updateById(u);
 System.out.println(row);
}
/**
 * 通过id查询
 */
@Test
void selectById(){
 //1.通过id来查询
 User u = userMapper.selectById(1l);
 System.out.println(u);

}

mybatis-plus有个特别好用的就是它的条件构造器,可以帮助我们构造常用的sql,具体用法我会贴在文章最后面。

/**
 * 通过条件构造器查询
 */
@Test
void selectByWrapper(){

 //3.通过条件构造器wrapper
 QueryWrapper qw = new QueryWrapper();
 qw.like("name","测试");
 qw.lt("age",50);//小于
 qw.gt("age",15);//大于

 List<User> us = userMapper.selectList(qw);
 us.stream().forEach(System.out::println);

}

既然有查询,自然少不了我们最关心的分页

/**
 * 通过条件构造器和page分页查询
 */
@Test
void selectByWrapperAndPage(){

 //4.通过条件构造器wrapper和Page分页查询
 QueryWrapper qw = new QueryWrapper();
 qw.like("name","测试");
 qw.lt("age",50);//小于
 qw.gt("age",15);//大于
 qw.orderByDesc("age");

 IPage<User> result = userMapper.selectPage(new Page<>(2,10),qw);
/**
 * 查询总记录数
 */
@Test
void selectCount(){

 //5.通过条件查询总条数
 QueryWrapper qw = new QueryWrapper();
 qw.like("name","测试");
 qw.lt("age",50);//小于
 qw.gt("age",15);//大于
 qw.orderByDesc("age");

 int count = userMapper.selectCount(qw);
 System.out.println(count);

}

删除

/**
 * 通过id删除
 */
@Test
void delete(){

 int row = userMapper.deleteById(27l);
 System.out.println(row);
}

/**
 * 通过id批量删除
 */
@Test
void deleteBatch(){

 int row = userMapper.deleteBatchIds(Arrays.asList(67l,44l,37l,220l));
 System.out.println(row);
}
/**
 * 通过条件删除
 */
@Test
void deleteByWrapper(){

 QueryWrapper<User> qw = new QueryWrapper<>();
 qw.gt("age",70);
 //先来看看有多少数据
 int row = userMapper.selectCount(qw);
 System.out.println(row);
 //删除
 int deleteRow = userMapper.delete(qw);
 System.out.println(deleteRow);
}

今天就到这,后续会给大家分享下mybatis-plus提供的sql性能执行分析插件、乐观锁插件以及字段的自动填充。

补充知识:Mybatis-plus 自动生成代码后xml文件和mapper映射不到的原因

报了如下错误

找了很久都没找到原因

2020-06-08 18:48:12 |ERROR |http-nio-8130-exec-3 |GlobalExceptionHandler.java:25 |service.base.handler.GlobalExceptionHandler |org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): service.used.mapper.ClassifyMapper.selectNestedListByParentId
	at org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:235)
	at com.baomidou.mybatisplus.core.override.MybatisMapperMethod.<init>(MybatisMapperMethod.java:50)
	at com.baomidou.mybatisplus.core.override.MybatisMapperProxy.lambda$cachedMapperMethod$0(MybatisMapperProxy.java:101)
	at java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1660)
	at com.baomidou.mybatisplus.core.override.MybatisMapperProxy.cachedMapperMethod(MybatisMapperProxy.java:100)
	at com.baomidou.mybatisplus.core.override.MybatisMapperProxy.invoke(MybatisMapperProxy.java:95)
	at com.sun.proxy.$Proxy98.selectNestedListByParentId(Unknown Source)
	at xyz.oneadd.platform.service.used.service.impl.ClassifyServiceImpl.nestedList(ClassifyServiceImpl.java:25)
	at xyz.oneadd.platform.service.used.service.impl.ClassifyServiceImpl$$FastClassBySpringCGLIB$$85da3417.invoke(<generated>)
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
	at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:685)
	at xyz.oneadd.platform.service.used.service.impl.ClassifyServiceImpl$$EnhancerBySpringCGLIB$$3b7bb86f.nestedList(<generated>)
	at xyz.oneadd.platform.service.used.controller.api.ApiClassifyController.classifyList(ApiClassifyController.java:34)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
	at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1591)
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Thread.java:748)

原因是pom中没有添加bulid依赖

添加依赖后解决问题

<build>
  <resources>
   <resource>
    <directory>src/main/java</directory>
    <includes>
     <include>**/*.xml</include>
    </includes>
    <filtering>false</filtering>
   </resource>
  </resources>
 </build>

以上这篇MybatisPlus,无XML分分钟实现CRUD操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持自学编程网。

编程技巧