您好,登錄后才能下訂單哦!
這篇文章主要介紹MybatisPlus無XML分分鐘實現(xiàn)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 '創(chuàng)建時間', `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("測試數(shù)據(jù)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("測試數(shù)據(jù)"+i); u.setAge((int)(Math.random()*90+10)); u.setPassword("mima"+i); us.add(u); } userService.saveBatch(us); }
其中用到了userService,我這里貼一下代碼,需要我們接口繼承Iservice,實現(xiàn)類繼承ServiceImple<M,T>,這樣就可以直接調用mybatis-plus為我們提供的現(xiàn)成方法了。
public interface IUserService extends IService<User> {
}
實現(xiàn)類
@Service public class UserServiceImpl extends ServiceImpl<UserDao, User>implements IUserService {
}
修改
/** * 修改 */ @Test void updateById(){ User u = new User(); //修改name u.setId(1L); u.setName("修改下數(shù)據(jù)--"); 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);
/** * 查詢總記錄數(shù) */ @Test void selectCount(){ //5.通過條件查詢總條數(shù) 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); //先來看看有多少數(shù)據(jù) int row = userMapper.selectCount(qw); System.out.println(row); //刪除 int deleteRow = userMapper.delete(qw); System.out.println(deleteRow); }
今天就到這,后續(xù)會給大家分享下mybatis-plus提供的sql性能執(zhí)行分析插件、樂觀鎖插件以及字段的自動填充。
補充知識: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分分鐘實現(xiàn)CRUD的方法是什么的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業(yè)資訊頻道!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。