“探索Spring与MyBatis集成的最佳实践与技巧“(下)

简介: “探索Spring与MyBatis集成的最佳实践与技巧“

1.4 配置MyBatis的SqlSessionFactory和MapperScannerConfigurer

BookMApper

package com.yuan.mapper;
import com.yuan.model.Book;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface BookMapper {
    int deleteByPrimaryKey(Integer bid);
    int insert(Book record);
    int insertSelective(Book record);
    Book selectByPrimaryKey(Integer bid);
    int updateByPrimaryKeySelective(Book record);
    int updateByPrimaryKey(Book record);
    List<Book> demo(Book book);
}
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9
• 10
• 11
• 12
• 13
• 14
• 15
• 16
• 17
• 18
• 19
• 20
• 21
• 22

BookBiz

package com.yuan.Biz.Impl;
import com.yuan.Biz.BookBiz;
import com.yuan.mapper.BookMapper;
import com.yuan.model.Book;
import com.yuan.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
 * @author 叶秋
 * @site
 * @company 卓京公司
 * @create 2023-08-25 16:40
 */
@Service
public class BookBizImpl implements BookBiz {
    @Autowired
    private BookMapper bookMapper;
    @Override
    public int deleteByPrimaryKey(Integer bid) {
        return bookMapper.deleteByPrimaryKey(bid);
    }
    @Override
    public int insert(Book record) {
        return bookMapper.insert(record);
    }
    @Override
    public int insertSelective(Book record) {
        return bookMapper.insertSelective(record);
    }
    @Override
    public Book selectByPrimaryKey(Integer bid) {
        return bookMapper.selectByPrimaryKey(bid);
    }
    @Override
    public int updateByPrimaryKeySelective(Book record) {
        return bookMapper.updateByPrimaryKeySelective(record);
    }
    @Override
    public int updateByPrimaryKey(Book record) {
        return bookMapper.updateByPrimaryKey(record);
    }
    @Override
    public List<Book> demo(Book book, PageBean pageBean) {
    return bookMapper.demo(book);
    }
}
• 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
• 57
• 58
• 59
• 60
• 61

BookBizImpl

package com.yuan.Biz.Impl;
import com.yuan.Biz.BookBiz;
import com.yuan.mapper.BookMapper;
import com.yuan.model.Book;
import com.yuan.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
 * @author 叶秋
 * @site
 * @company 卓京公司
 * @create 2023-08-25 16:40
 */
@Service
public class BookBizImpl implements BookBiz {
    @Autowired
    private BookMapper bookMapper;
    @Override
    public int deleteByPrimaryKey(Integer bid) {
        return bookMapper.deleteByPrimaryKey(bid);
    }
    @Override
    public int insert(Book record) {
        return bookMapper.insert(record);
    }
    @Override
    public int insertSelective(Book record) {
        return bookMapper.insertSelective(record);
    }
    @Override
    public Book selectByPrimaryKey(Integer bid) {
        return bookMapper.selectByPrimaryKey(bid);
    }
    @Override
    public int updateByPrimaryKeySelective(Book record) {
        return bookMapper.updateByPrimaryKeySelective(record);
    }
    @Override
    public int updateByPrimaryKey(Book record) {
        return bookMapper.updateByPrimaryKey(record);
    }
    @Override
    public List<Book> demo(Book book, PageBean pageBean) {
    return bookMapper.demo(book);
    }
}
• 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
• 57
• 58
• 59
• 60
• 61

测试

package com.yuan.Biz.Impl;
import com.yuan.Biz.BookBiz;
import com.yuan.model.Book;
import com.yuan.utils.PageBean;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
 * @author 叶秋
 * @site
 * @company 卓京公司
 * @create 2023-08-25 16:43
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-context.xml"})
public class BookBizImplTest {
    @Autowired
    private BookBiz bookBiz;
    @Test
    public void selectByPrimaryKey() {
        System.out.println(this.bookBiz.selectByPrimaryKey(45));
    }
}
• 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

打印结果

2.Spring aop集成pagehelper插件

pageBean

package com.yuan.utils;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Map;
public class PageBean implements Serializable {
  private static final long serialVersionUID = 2422581023658455731L;
  //页码
  private int page=1;
  //每页显示记录数
  private int rows=10;
  //总记录数
  private int total=0;
  //是否分页
  private boolean isPagination=true;
  //上一次的请求路径
  private String url;
  //获取所有的请求参数
  private Map<String,String[]> map;
  public PageBean() {
    super();
  }
  //设置请求参数
  public void setRequest(HttpServletRequest req) {
    String page=req.getParameter("page");
    String rows=req.getParameter("rows");
    String pagination=req.getParameter("pagination");
    this.setPage(page);
    this.setRows(rows);
    this.setPagination(pagination);
    this.url=req.getContextPath()+req.getServletPath();
    this.map=req.getParameterMap();
  }
  public String getUrl() {
    return url;
  }
  public void setUrl(String url) {
    this.url = url;
  }
  public Map<String, String[]> getMap() {
    return map;
  }
  public void setMap(Map<String, String[]> map) {
    this.map = map;
  }
  public int getPage() {
    return page;
  }
  public void setPage(int page) {
    this.page = page;
  }
  public void setPage(String page) {
    if(null!=page&&!"".equals(page.trim()))
      this.page = Integer.parseInt(page);
  }
  public int getRows() {
    return rows;
  }
  public void setRows(int rows) {
    this.rows = rows;
  }
  public void setRows(String rows) {
    if(null!=rows&&!"".equals(rows.trim()))
      this.rows = Integer.parseInt(rows);
  }
  public int getTotal() {
    return total;
  }
  public void setTotal(int total) {
    this.total = total;
  }
  public void setTotal(String total) {
    this.total = Integer.parseInt(total);
  }
  public boolean isPagination() {
    return isPagination;
  }
  public void setPagination(boolean isPagination) {
    this.isPagination = isPagination;
  }
  public void setPagination(String isPagination) {
    if(null!=isPagination&&!"".equals(isPagination.trim()))
      this.isPagination = Boolean.parseBoolean(isPagination);
  }
  /**
   * 获取分页起始标记位置
   * @return
   */
  public int getStartIndex() {
    //(当前页码-1)*显示记录数
    return (this.getPage()-1)*this.rows;
  }
  /**
   * 末页
   * @return
   */
  public int getMaxPage() {
    int totalpage=this.total/this.rows;
    if(this.total%this.rows!=0)
      totalpage++;
    return totalpage;
  }
  /**
   * 下一页
   * @return
   */
  public int getNextPage() {
    int nextPage=this.page+1;
    if(this.page>=this.getMaxPage())
      nextPage=this.getMaxPage();
    return nextPage;
  }
  /**
   * 上一页
   * @return
   */
  public int getPreivousPage() {
    int previousPage=this.page-1;
    if(previousPage<1)
      previousPage=1;
    return previousPage;
  }
  @Override
  public String toString() {
    return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", isPagination=" + isPagination
        + "]";
  }
}
• 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
• 57
• 58
• 59
• 60
• 61
• 62
• 63
• 64
• 65
• 66
• 67
• 68
• 69
• 70
• 71
• 72
• 73
• 74
• 75
• 76
• 77
• 78
• 79
• 80
• 81
• 82
• 83
• 84
• 85
• 86
• 87
• 88
• 89
• 90
• 91
• 92
• 93
• 94
• 95
• 96
• 97
• 98
• 99
• 100
• 101
• 102
• 103
• 104
• 105
• 106
• 107
• 108
• 109
• 110
• 111
• 112
• 113
• 114
• 115
• 116
• 117
• 118
• 119
• 120
• 121
• 122
• 123
• 124
• 125
• 126
• 127
• 128
• 129
• 130
• 131
• 132
• 133
• 134
• 135
• 136
• 137
• 138
• 139
• 140
• 141
• 142
• 143
• 144
• 145
• 146
• 147
• 148
• 149
• 150
• 151
• 152
• 153
• 154

PagerAspect

package com.yuan.aspect;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuan.utils.PageBean;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import java.util.List;
/**
 * @author 叶秋
 * @site
 * @company 卓京公司
 * @create 2023-08-25 17:01
 */
@Aspect
@Component
public class PagerAspect {
    @Around("execution(* *..*Biz.*Pager(..))")
    public Object invoke(ProceedingJoinPoint args) throws Throwable {
        PageBean pageBean = null;
        //获取目标中的所有方法
        Object[] args1 = args.getArgs();
        for (Object o : args1) {
            if (o instanceof PageBean) {
                pageBean = (PageBean) o;
                break;
            }
        }
        if (pageBean != null && pageBean.isPagination()) {
            PageHelper.startPage(pageBean.getPage(), pageBean.getRows());
        }
        Object proceed = args.proceed();
        if (pageBean != null && pageBean.isPagination()) {
            PageInfo pageInfo = new PageInfo((List) proceed);
            pageBean.setTotal((int) pageInfo.getTotal());
        }
        return proceed;
        }
}
• 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

测试方法

@Test
    public void list() {
        Book book = new Book();
        book.setBname("圣墟");
        PageBean pageBean = new PageBean();
        pageBean.setPage(2);
        pageBean.setRows(20);
        this.bookBiz.demo(book,pageBean).forEach(System.out::println);
    }
• 1
• 2
• 3
• 4
• 5
• 6
• 7
• 8
• 9

打印结果

总结

本文深入探讨了Spring与MyBatis集成的最佳实践与技巧。我们学习了如何进行基本配置,使用Spring管理MyBatis的Mapper,使用Spring的事务管理器管理MyBatis的事务,以及如何使用Spring的AOP功能增强MyBatis的功能。通过合理地使用这些技术,我们可以提高应用程序的性能和可维护性。

在实际开发中,我们应该根据具体的需求和项目规模来选择合适的集成方式,并结合项目的实际情况进行调优和优化。希望本文对您在Spring与MyBatis集成方面的学习和实践有所帮助。

附带内容:

在实际项目中,Spring与MyBatis的集成是非常常见的。通过将两个框架结合使用,我们可以充分发挥它们各自的优势,提高开发效率和代码质量。

  • 在配置Spring与MyBatis集成时,我们需要注意以下几点:
  • 确保正确引入Spring和MyBatis的依赖,版本兼容性是非常重要的。
  • 配置数据源和事务管理器时,需要根据实际情况选择合适的实现。
  • 在使用Spring管理MyBatis的Mapper时,可以选择使用@Mapper注解或
  • MapperScannerConfigurer扫描Mapper接口。
  • 在使用Spring的事务管理器管理MyBatis的事务时,需要注意事务的传播行为和隔离级别的设置。
  • 使用Spring的AOP功能增强MyBatis的功能时,可以定义切面类并配置切点和通知,以实现对Mapper方法的增强。

总之,Spring与MyBatis的集成可以帮助我们更好地组织和管理代码,提高开发效率和代码质量。通过深入学习和实践,我们可以掌握集成的最佳实践与技巧,为项目的成功实施提供有力支持。


目录
打赏
0
0
0
0
4
分享
相关文章
|
4月前
|
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 身份和权限认证
本文介绍了 Apache Shiro 的身份认证与权限认证机制。在身份认证部分,分析了 Shiro 的认证流程,包括应用程序调用 `Subject.login(token)` 方法、SecurityManager 接管认证以及通过 Realm 进行具体的安全验证。权限认证部分阐述了权限(permission)、角色(role)和用户(user)三者的关系,其中用户可拥有多个角色,角色则对应不同的权限组合,例如普通用户仅能查看或添加信息,而管理员可执行所有操作。
157 0
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 三大核心组件
本课程介绍如何在Spring Boot中集成Shiro框架,主要讲解Shiro的认证与授权功能。Shiro是一个简单易用的Java安全框架,用于认证、授权、加密和会话管理等。其核心组件包括Subject(认证主体)、SecurityManager(安全管理员)和Realm(域)。Subject负责身份认证,包含Principals(身份)和Credentials(凭证);SecurityManager是架构核心,协调内部组件运作;Realm则是连接Shiro与应用数据的桥梁,用于访问用户账户及权限信息。通过学习,您将掌握Shiro的基本原理及其在项目中的应用。
155 0
Spring boot 使用mybatis generator 自动生成代码插件
本文介绍了在Spring Boot项目中使用MyBatis Generator插件自动生成代码的详细步骤。首先创建一个新的Spring Boot项目,接着引入MyBatis Generator插件并配置`pom.xml`文件。然后删除默认的`application.properties`文件,创建`application.yml`进行相关配置,如设置Mapper路径和实体类包名。重点在于配置`generatorConfig.xml`文件,包括数据库驱动、连接信息、生成模型、映射文件及DAO的包名和位置。最后通过IDE配置运行插件生成代码,并在主类添加`@MapperScan`注解完成整合
Spring boot 使用mybatis generator 自动生成代码插件
|
1月前
|
解决Java Spring Boot应用中MyBatis-Plus查询问题的策略。
保持技能更新是侦探的重要素质。定期回顾最佳实践和新技术。比如,定期查看MyBatis-Plus的更新和社区的最佳做法,这样才能不断提升查询效率和性能。
85 1
【Azure Application Insights】为Spring Boot应用集成Application Insight SDK
本文以Java Spring Boot项目为例,详细说明如何集成Azure Application Insights SDK以收集和展示日志。内容包括三步配置:1) 在`pom.xml`中添加依赖项`applicationinsights-runtime-attach`和`applicationinsights-core`;2) 在main函数中调用`ApplicationInsights.attach()`;3) 配置`applicationinsights.json`文件。同时提供问题排查建议及自定义日志方法示例,帮助用户顺利集成并使用Application Insights服务。
深入解析HTTP请求方法:Spring Boot实战与最佳实践
这篇博客结合了HTTP规范、Spring Boot实现和实际工程经验,通过代码示例、对比表格和架构图等方式,系统性地讲解了不同HTTP方法的应用场景和最佳实践。
272 5
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——ActiveMQ安装
本教程介绍ActiveMQ的安装与基本使用。首先从官网下载apache-activemq-5.15.3版本,解压后即可完成安装,非常便捷。启动时进入解压目录下的bin文件夹,根据系统选择win32或win64,运行activemq.bat启动服务。通过浏览器访问`http://127.0.0.1:8161/admin/`可进入管理界面,默认用户名密码为admin/admin。ActiveMQ支持两种消息模式:点对点(Queue)和发布/订阅(Topic)。前者确保每条消息仅被一个消费者消费,后者允许多个消费者同时接收相同消息。
110 0
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——ActiveMQ安装
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——发布/订阅消息的生产和消费
本文详细讲解了Spring Boot中ActiveMQ的发布/订阅消息机制,包括消息生产和消费的具体实现方式。生产端通过`sendMessage`方法发送订阅消息,消费端则需配置`application.yml`或自定义工厂以支持topic消息监听。为解决点对点与发布/订阅消息兼容问题,可通过设置`containerFactory`实现两者共存。最后,文章还提供了测试方法及总结,帮助读者掌握ActiveMQ在异步消息处理中的应用。
139 0
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——ActiveMQ集成
本文介绍了在 Spring Boot 中集成 ActiveMQ 的详细步骤。首先通过引入 `spring-boot-starter-activemq` 依赖并配置 `application.yml` 文件实现基本设置。接着,创建 Queue 和 Topic 消息类型,分别使用 `ActiveMQQueue` 和 `ActiveMQTopic` 类完成配置。随后,利用 `JmsMessagingTemplate` 实现消息发送功能,并通过 Controller 和监听器实现点对点消息的生产和消费。最后,通过浏览器访问测试接口验证消息传递的成功性。
128 0
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ—— JMS 和 ActiveMQ 介绍
本文介绍如何在Spring Boot中集成ActiveMQ,首先阐述了JMS(Java消息服务)的概念及其作为与具体平台无关的API在异步通信中的作用。接着说明了JMS的主要对象模型,如连接工厂、会话、生产者和消费者等,并指出JMS支持点对点和发布/订阅两种消息类型。随后重点讲解了ActiveMQ,作为Apache开源的消息总线,它完全支持JMS规范,适用于异步消息处理。最后,文章探讨了在Spring Boot中使用队列(Queue)和主题(Topic)这两种消息通信形式的方法。
97 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问