中国企业网站建设现状,成都网站建设scdzks,在线购物商城平台,免费网站专业建站目录
一.Spring整合Mybatis
1.什么是Spring整合Mybatis
新建一个ssm
编辑 导入pom依赖 导入generatorConfig.xml
导入Spring-context.xml文件
导入Spring-mybatis.xml文件 自动生成Bookmapper.xml和Bookmapper文件 编写接口类#xff1a;Bookbiz
编写接口实现类
…
目录
一.Spring整合Mybatis
1.什么是Spring整合Mybatis
新建一个ssm
编辑 导入pom依赖 导入generatorConfig.xml
导入Spring-context.xml文件
导入Spring-mybatis.xml文件 自动生成Bookmapper.xml和Bookmapper文件 编写接口类Bookbiz
编写接口实现类
编写实体类
编辑
编写接口测试类
测试结果
二.aop整合pageHelper分页插件
1.什么是aop整合pageHelper分页插件
编写分页查询
编辑
编写PageBean
编写PagerAspect类
测试结果 一.Spring整合Mybatis
1.什么是Spring整合Mybatis Spring整合MyBatis是一种常用的Java后端开发技术用于将Spring框架与MyBatis框架进行集成实现更方便和高效地操作数据库。 Spring框架是一个功能强大的轻量级应用程序开发框架它提供了依赖注入DI和面向切面编程AOP等特性可以帮助开发者更好地管理和组织应用程序的组件。 MyBatis是一个优秀的持久层框架它通过XML或注解的方式将SQL语句与Java对象之间的映射关系定义起来提供了灵活的数据访问和数据库操作功能。 Spring整合MyBatis的主要目的是通过Spring的依赖注入和事务管理等特性简化MyBatis的配置和代码编写。通过集成可以将MyBatis作为Spring的一个Bean来管理通过注入的方式获取MyBatis的SqlSessionFactory从而简化数据库操作的配置和调用。 具体来说Spring整合MyBatis的步骤包括以下几个方面 引入相关的依赖包括Spring框架和MyBatis框架的依赖配置Spring的配置文件包括定义数据源、事务管理器等Bean并引入MyBatis的配置文件配置MyBatis的配置文件定义数据库连接信息、映射文件等编写DAO接口和Mapper文件定义数据库操作的接口和SQL语句在Spring的配置文件中配置MyBatis的Mapper扫描和注入。 通过Spring整合MyBatis开发者可以充分利用两个框架的优势实现数据库操作的便捷和高效。 新建一个ssm 导入pom依赖
?xml version1.0 encodingUTF-8?project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersiongroupIdcom.zking/groupIdartifactIdyxssm/artifactIdversion1.0-SNAPSHOT/versionpackagingwar/packagingnameyxssm Maven Webapp/name!-- FIXME change it to the projects website --urlhttp://www.example.com/urlpropertiesproject.build.sourceEncodingUTF-8/project.build.sourceEncodingmaven.compiler.source1.8/maven.compiler.sourcemaven.compiler.target1.8/maven.compiler.targetmaven.compiler.plugin.version3.7.0/maven.compiler.plugin.version!--添加jar包依赖--!--1.spring 5.0.2.RELEASE相关--spring.version5.0.2.RELEASE/spring.version!--2.mybatis相关--mybatis.version3.4.5/mybatis.version!--mysql--mysql.version5.1.44/mysql.version!--pagehelper分页jar依赖--pagehelper.version5.1.2/pagehelper.version!--mybatis与spring集成jar依赖--mybatis.spring.version1.3.1/mybatis.spring.version!--3.dbcp2连接池相关 druid--commons.dbcp2.version2.1.1/commons.dbcp2.versioncommons.pool2.version2.4.3/commons.pool2.version!--4.log日志相关--log4j2.version2.9.1/log4j2.version!--5.其他--junit.version4.12/junit.versionservlet.version4.0.0/servlet.versionlombok.version1.18.2/lombok.version/propertiesdependencies!--1.spring相关--dependencygroupIdorg.springframework/groupIdartifactIdspring-context/artifactIdversion${spring.version}/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-orm/artifactIdversion${spring.version}/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-tx/artifactIdversion${spring.version}/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-aspects/artifactIdversion${spring.version}/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-web/artifactIdversion${spring.version}/version/dependencydependencygroupIdorg.springframework/groupIdartifactIdspring-test/artifactIdversion${spring.version}/version/dependency!--2.mybatis相关--dependencygroupIdorg.mybatis/groupIdartifactIdmybatis/artifactIdversion${mybatis.version}/version/dependency!--mysql--dependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdversion${mysql.version}/version/dependency!--pagehelper分页插件jar包依赖--dependencygroupIdcom.github.pagehelper/groupIdartifactIdpagehelper/artifactIdversion${pagehelper.version}/version/dependency!--mybatis与spring集成jar包依赖--dependencygroupIdorg.mybatis/groupIdartifactIdmybatis-spring/artifactIdversion${mybatis.spring.version}/version/dependency!--3.dbcp2连接池相关--dependencygroupIdorg.apache.commons/groupIdartifactIdcommons-dbcp2/artifactIdversion${commons.dbcp2.version}/version/dependencydependencygroupIdorg.apache.commons/groupIdartifactIdcommons-pool2/artifactIdversion${commons.pool2.version}/version/dependency!--4.log日志相关依赖--!--核心log4j2jar包--dependencygroupIdorg.apache.logging.log4j/groupIdartifactIdlog4j-core/artifactIdversion${log4j2.version}/version/dependencydependencygroupIdorg.apache.logging.log4j/groupIdartifactIdlog4j-api/artifactIdversion${log4j2.version}/version/dependency!--web工程需要包含log4j-web非web工程不需要--dependencygroupIdorg.apache.logging.log4j/groupIdartifactIdlog4j-web/artifactIdversion${log4j2.version}/version/dependency!--5.其他--dependencygroupIdjunit/groupIdartifactIdjunit/artifactIdversion${junit.version}/version!--scopetest/scope--/dependencydependencygroupIdjavax.servlet/groupIdartifactIdjavax.servlet-api/artifactIdversion${servlet.version}/versionscopeprovided/scope/dependencydependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactIdversion${lombok.version}/versionscopeprovided/scope/dependency/dependenciesbuildfinalNameyxssm/finalNameresources!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题--resourcedirectorysrc/main/java/directoryincludesinclude**/*.xml/include/includes/resource!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题--resourcedirectorysrc/main/resources/directoryincludesincludejdbc.properties/includeinclude*.xml/include/includes/resource/resourcespluginsplugingroupIdorg.apache.maven.plugins/groupIdartifactIdmaven-compiler-plugin/artifactIdversion${maven.compiler.plugin.version}/versionconfigurationsource${maven.compiler.source}/sourcetarget${maven.compiler.target}/targetencoding${project.build.sourceEncoding}/encoding/configuration/pluginplugingroupIdorg.mybatis.generator/groupIdartifactIdmybatis-generator-maven-plugin/artifactIdversion1.3.2/versiondependencies!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 --dependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdversion${mysql.version}/version/dependency/dependenciesconfigurationoverwritetrue/overwrite/configuration/pluginpluginartifactIdmaven-clean-plugin/artifactIdversion3.1.0/version/plugin!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --pluginartifactIdmaven-resources-plugin/artifactIdversion3.0.2/version/pluginpluginartifactIdmaven-compiler-plugin/artifactIdversion3.8.0/version/pluginpluginartifactIdmaven-surefire-plugin/artifactIdversion2.22.1/version/pluginpluginartifactIdmaven-war-plugin/artifactIdversion3.2.2/version/pluginpluginartifactIdmaven-install-plugin/artifactIdversion2.5.2/version/pluginpluginartifactIdmaven-deploy-plugin/artifactIdversion2.8.2/version/plugin/plugins/build
/project导入generatorConfig.xml
?xml version1.0 encodingUTF-8 ?
!DOCTYPE generatorConfiguration PUBLIC -//mybatis.org//DTD MyBatis Generator Configuration 1.0//ENhttp://mybatis.org/dtd/mybatis-generator-config_1_0.dtd
generatorConfiguration!-- 引入配置文件 --properties resourcejdbc.properties/!--指定数据库jdbc驱动jar包的位置--classPathEntry locationC:\\temp2\\mvn_repository\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar/!-- 一个数据库一个context --context idinfoGuardian!-- 注释 --commentGeneratorproperty namesuppressAllComments valuetrue/!-- 是否取消注释 --property namesuppressDate valuetrue/ !-- 是否生成注释代时间戳 --/commentGenerator!-- jdbc连接 --jdbcConnection driverClass${jdbc.driver}connectionURL${jdbc.url} userId${jdbc.username} password${jdbc.password}/!-- 类型转换 --javaTypeResolver!-- 是否使用bigDecimal false可自动转化以下类型Long, Integer, Short, etc. --property nameforceBigDecimals valuefalse//javaTypeResolver!-- 01 指定javaBean生成的位置 --!-- targetPackage指定生成的model生成所在的包名 --!-- targetProject指定在该项目下所在的路径 --javaModelGenerator targetPackagecom.zking.modeltargetProjectsrc/main/java!-- 是否允许子包即targetPackage.schemaName.tableName --property nameenableSubPackages valuefalse/!-- 是否对model添加构造函数 --property nameconstructorBased valuetrue/!-- 是否针对string类型的字段在set的时候进行trim调用 --property nametrimStrings valuefalse/!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法只有构造方法 --property nameimmutable valuefalse//javaModelGenerator!-- 02 指定sql映射文件生成的位置 --sqlMapGenerator targetPackagecom.zking.mappertargetProjectsrc/main/java!-- 是否允许子包即targetPackage.schemaName.tableName --property nameenableSubPackages valuefalse//sqlMapGenerator!-- 03 生成XxxMapper接口 --!-- typeANNOTATEDMAPPER,生成Java Model 和基于注解的Mapper对象 --!-- typeMIXEDMAPPER,生成基于注解的Java Model 和相应的Mapper对象 --!-- typeXMLMAPPER,生成SQLMap XML文件和独立的Mapper接口 --javaClientGenerator targetPackagecom.zking.mappertargetProjectsrc/main/java typeXMLMAPPER!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model true:com.oop.eksp.user.model.[schemaName] --property nameenableSubPackages valuefalse//javaClientGenerator!-- 配置表信息 --!-- schema即为数据库名 --!-- tableName为对应的数据库表 --!-- domainObjectName是要生成的实体类 --!-- enable*ByExample是否生成 example类 --!--table schema tableNamet_book domainObjectNameBook--!--enableCountByExamplefalse enableDeleteByExamplefalse--!--enableSelectByExamplefalse enableUpdateByExamplefalse--!--lt;!ndash; 忽略列不生成bean 字段 ndash;gt;--!--lt;!ndash; ignoreColumn columnFRED / ndash;gt;--!--lt;!ndash; 指定列的java数据类型 ndash;gt;--!--lt;!ndash; columnOverride columnLONG_VARCHAR_FIELD jdbcTypeVARCHAR / ndash;gt;--!--/table--table schema tableNamet_mvc_Book domainObjectNameBookenableCountByExamplefalse enableDeleteByExamplefalseenableSelectByExamplefalse enableUpdateByExamplefalse!-- 忽略列不生成bean 字段 --!-- ignoreColumn columnFRED / --!-- 指定列的java数据类型 --!-- columnOverride columnLONG_VARCHAR_FIELD jdbcTypeVARCHAR / --/table/context
/generatorConfiguration导入Spring-context.xml文件
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd!--spring框架与mybatis整合的配置文件加载到spring的上下文件中--import resourceclasspath:spring-mybatis.xml/import
/beans
导入Spring-mybatis.xml文件
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/context xmlns:txhttp://www.springframework.org/schema/txxmlns:aophttp://www.springframework.org/schema/aopxsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd!--1. 注解式开发 --!-- 注解驱动 --context:annotation-config/!-- 用注解方式注入bean并指定查找范围com.javaxl.ssm及子子孙孙包--context:component-scan base-packagecom.zking/context:property-placeholder locationclasspath:jdbc.properties/bean iddataSource classorg.apache.commons.dbcp2.BasicDataSourcedestroy-methodcloseproperty namedriverClassName value${jdbc.driver}/property nameurl value${jdbc.url}/property nameusername value${jdbc.username}/property namepassword value${jdbc.password}/!--初始连接数--property nameinitialSize value10/!--最大活动连接数--property namemaxTotal value100/!--最大空闲连接数--property namemaxIdle value50/!--最小空闲连接数--property nameminIdle value10/!--设置为-1时如果没有可用连接连接池会一直无限期等待直到获取到连接为止。--!--如果设置为N毫秒则连接池会等待N毫秒等待不到则抛出异常--property namemaxWaitMillis value-1//bean!--4. spring和MyBatis整合 --!--1) 创建sqlSessionFactory--bean idsqlSessionFactory classorg.mybatis.spring.SqlSessionFactoryBean!-- 指定数据源 --property namedataSource refdataSource/!-- 自动扫描XxxMapping.xml文件**任意路径 --property namemapperLocations valueclasspath*:com/zking/**/mapper/*.xml/!-- 指定别名 --property nametypeAliasesPackage valuecom/zking/ssm/**/model/!--配置pagehelper插件--property namepluginsarraybean classcom.github.pagehelper.PageInterceptorproperty namepropertiesvaluehelperDialectmysql/value/property/bean/array/property/bean!--2) 自动扫描com/javaxl/ssm/**/mapper下的所有XxxMapper接口(其实就是DAO接口)并实现这些接口--!-- 即可直接在程序中使用dao接口不用再获取sqlsession对象--bean classorg.mybatis.spring.mapper.MapperScannerConfigurer!--basePackage 属性是映射器接口文件的包路径。--!--你可以使用分号或逗号 作为分隔符设置多于一个的包路径--property namebasePackage valuecom/zking/**/mapper/property namesqlSessionFactoryBeanName valuesqlSessionFactory//beanbean idtransactionManager classorg.springframework.jdbc.datasource.DataSourceTransactionManagerproperty namedataSource refdataSource //beantx:annotation-driven transaction-managertransactionManager /aop:aspectj-autoproxy/
/beans自动生成Bookmapper.xml和Bookmapper文件 注意右边的mybatis-generator:generate点一次就OK了点了两次他就会生成两个Bookmapper.xml文件 编写接口类Bookbiz
package com.zking.biz;import com.zking.model.Book;/*** author bing人* site* company xy集团* create 2023-08-25 14:57*/
public interface BookBiz {int deleteByPrimaryKey(Integer bid);int insert(Book record);int insertSelective(Book record);Book selectByPrimaryKey(Integer bid);int updateByPrimaryKeySelective(Book record);int updateByPrimaryKey(Book record);
}编写接口实现类
package com.zking.biz.impl;import com.zking.biz.BookBiz;
import com.zking.mapper.BookMapper;
import com.zking.model.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;/*** author bing人* site* company xy集团* create 2023-08-25 15:00*/
Service
public class BookBizImpl implements BookBiz {Autowiredprivate BookMapper bookMapper;Overridepublic int deleteByPrimaryKey(Integer bid) {return bookMapper.deleteByPrimaryKey(bid);}Overridepublic int insert(Book record) {return bookMapper.insert(record);}Overridepublic int insertSelective(Book record) {return bookMapper.insertSelective(record);}Overridepublic Book selectByPrimaryKey(Integer bid) {return bookMapper.selectByPrimaryKey(bid);}Overridepublic int updateByPrimaryKeySelective(Book record) {return updateByPrimaryKeySelective(record);}Overridepublic int updateByPrimaryKey(Book record) {return bookMapper.updateByPrimaryKey(record);}
}编写实体类 编写接口测试类
package com.zking.biz.impl;import com.zking.biz.BookBiz;
import com.zking.model.Book;
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;import static org.junit.Assert.*;/*** author bing人* site* company xy集团* create 2023-08-25 15:06*/
//自动加载上下文
RunWith(SpringJUnit4ClassRunner.class)
ContextConfiguration(locations{classpath:spring-context.xml})
public class BookBizImplTest {Autowiredprivate BookBiz bookBiz;Beforepublic void setUp() throws Exception {}Afterpublic void tearDown() throws Exception {}Testpublic void deleteByPrimaryKey() {this.bookBiz.deleteByPrimaryKey(41);}Testpublic void insert() {}Testpublic void insertSelective() {}Testpublic void selectByPrimaryKey() {System.out.println(this.bookBiz.selectByPrimaryKey(41));}Testpublic void updateByPrimaryKeySelective() {}Testpublic void updateByPrimaryKey() {}
}
测试结果 二.aop整合pageHelper分页插件
1.什么是aop整合pageHelper分页插件 AOP整合PageHelper分页插件的目的是为了在应用程序中实现自动分页的功能减少代码的重复编写和维护工作。通过AOP的方式可以在方法执行前拦截方法调用并在拦截器中加入PageHelper的分页逻辑。 具体来说AOP整合PageHelper分页插件的步骤如下 引入相关依赖包括Spring框架、MyBatis框架、PageHelper插件等配置PageHelper的属性如数据库类型、分页参数等编写AOP切面类使用AOP的注解或者XML配置定义切面逻辑在切面中拦截需要分页的方法并使用PageHelper.startPage()方法来进行分页设置在DAO层的方法上添加分页查询相关的注解如Select、SelectProvider等。 通过AOP整合PageHelper分页插件可以简化分页查询的代码编写使得业务逻辑更加清晰和可维护。同时该方式也可以方便地对分页参数进行统一管理和配置。 编写分页查询 编写PageBean
package com.zking.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 page1;//每页显示记录数private int rows10;//总记录数private int total0;//是否分页private boolean isPaginationtrue;//上一次的请求路径private String url;//获取所有的请求参数private MapString,String[] map;public PageBean() {super();}//设置请求参数public void setRequest(HttpServletRequest req) {String pagereq.getParameter(page);String rowsreq.getParameter(rows);String paginationreq.getParameter(pagination);this.setPage(page);this.setRows(rows);this.setPagination(pagination);this.urlreq.getContextPath()req.getServletPath();this.mapreq.getParameterMap();}public String getUrl() {return url;}public void setUrl(String url) {this.url url;}public MapString, String[] getMap() {return map;}public void setMap(MapString, 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 totalpagethis.total/this.rows;if(this.total%this.rows!0)totalpage;return totalpage;}/*** 下一页* return*/public int getNextPage() {int nextPagethis.page1;if(this.pagethis.getMaxPage())nextPagethis.getMaxPage();return nextPage;}/*** 上一页* return*/public int getPreivousPage() {int previousPagethis.page-1;if(previousPage1)previousPage1;return previousPage;}Overridepublic String toString() {return PageBean [page page , rows rows , total total , isPagination isPagination ];}}编写PagerAspect类
package com.zking.aspect;import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zking.model.Book;
import com.zking.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 bing人* site* company xy集团* create 2023-08-25 16:33*/
Aspect //代表当前类为切面类
Component //代表当前类交给spring进行管理
public class PagerAspect {Around(execution(* *..*Biz.*Pager(..)))public Object invoke(ProceedingJoinPoint args) throws Throwable{PageBean pageBeannull;//获取目标方法中的所有参数Object[] ags args.getArgs();for (Object param : ags) {if(param instanceof PageBean){pageBean (PageBean) param;break;}}if(pageBean !null pageBean.isPagination())PageHelper.startPage(pageBean.getPage(),pageBean.getRows());//执行目标方法Object lst args.proceed();if(pageBean !null pageBean.isPagination()){PageInfo info new PageInfo((List) lst);pageBean.setTotal((int)info.getTotal());}return lst;}}测试结果