MyBatis与Spring集成
导入pom依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>Spring</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version> <!--添加jar包依赖--> <!--1.spring 5.0.2.RELEASE相关--> <spring.version>5.0.2.RELEASE</spring.version> <!--2.mybatis相关--> <mybatis.version>3.4.5</mybatis.version> <!--mysql--> <mysql.version>5.1.44</mysql.version> <!--pagehelper分页jar依赖--> <pagehelper.version>5.1.2</pagehelper.version> <!--mybatis与spring集成jar依赖--> <mybatis.spring.version>1.3.1</mybatis.spring.version> <!--3.dbcp2连接池相关 druid--> <commons.dbcp2.version>2.1.1</commons.dbcp2.version> <commons.pool2.version>2.4.3</commons.pool2.version> <!--4.log日志相关--> <log4j2.version>2.9.1</log4j2.version> <!--5.其他--> <junit.version>4.12</junit.version> <servlet.version>4.0.0</servlet.version> <lombok.version>1.18.2</lombok.version> </properties> <dependencies> <!--1.spring相关--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!--2.mybatis相关--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!--pagehelper分页插件jar包依赖--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>${pagehelper.version}</version> </dependency> <!--mybatis与spring集成jar包依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <!--3.dbcp2连接池相关--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>${commons.dbcp2.version}</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>${commons.pool2.version}</version> </dependency> <!--4.log日志相关依赖--> <!--核心log4j2jar包--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>${log4j2.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>${log4j2.version}</version> </dependency> <!--web工程需要包含log4j-web,非web工程不需要--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-web</artifactId> <version>${log4j2.version}</version> </dependency> <!--5.其他--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <!-- <scope>test</scope>--> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>Spring</finalName> <resources> <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题--> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题--> <resource> <directory>src/main/resources</directory> <includes> <include>jdbc.properties</include> <include>*.xml</include> </includes> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven.compiler.plugin.version}</version> <configuration> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <dependencies> <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> </dependencies> <configuration> <overwrite>true</overwrite> </configuration> </plugin> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </build> </project>
导入generatorConfig.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > <generatorConfiguration> <!-- 引入配置文件 --> <properties resource="jdbc.properties"/> <!--指定数据库jdbc驱动jar包的位置--> <classPathEntry location="D:\\temp2\\mvn_repository\\mysql\\mysql-connector-java\\5.1.44"/> <!-- 一个数据库一个context --> <context id="infoGuardian"> <!-- 注释 --> <commentGenerator> <property name="suppressAllComments" value="true"/><!-- 是否取消注释 --> <property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 --> </commentGenerator> <!-- jdbc连接 --> <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/> <!-- 类型转换 --> <javaTypeResolver> <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) --> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 01 指定javaBean生成的位置 --> <!-- targetPackage:指定生成的model生成所在的包名 --> <!-- targetProject:指定在该项目下所在的路径 --> <javaModelGenerator targetPackage="com.xiaoxu.model" targetProject="src/main/java"> <!-- 是否允许子包,即targetPackage.schemaName.tableName --> <property name="enableSubPackages" value="false"/> <!-- 是否对model添加构造函数 --> <property name="constructorBased" value="true"/> <!-- 是否针对string类型的字段在set的时候进行trim调用 --> <property name="trimStrings" value="false"/> <!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 --> <property name="immutable" value="false"/> </javaModelGenerator> <!-- 02 指定sql映射文件生成的位置 --> <sqlMapGenerator targetPackage="com.xiaoxu.mapper" targetProject="src/main/java"> <!-- 是否允许子包,即targetPackage.schemaName.tableName --> <property name="enableSubPackages" value="false"/> </sqlMapGenerator> <!-- 03 生成XxxMapper接口 --> <!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 --> <!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 --> <!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 --> <javaClientGenerator targetPackage="com.xiaoxu.mapper" targetProject="src/main/java" type="XMLMAPPER"> <!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --> <property name="enableSubPackages" value="false"/> </javaClientGenerator> <!-- 配置表信息 --> <!-- schema即为数据库名 --> <!-- tableName为对应的数据库表 --> <!-- domainObjectName是要生成的实体类 --> <!-- enable*ByExample是否生成 example类 --> <!--<table schema="" tableName="t_book" domainObjectName="Book"--> <!--enableCountByExample="false" enableDeleteByExample="false"--> <!--enableSelectByExample="false" enableUpdateByExample="false">--> <!--<!– 忽略列,不生成bean 字段 –>--> <!--<!– <ignoreColumn column="FRED" /> –>--> <!--<!– 指定列的java数据类型 –>--> <!--<!– <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> –>--> <!--</table>--> <table schema="" tableName="t_mvc_Book" domainObjectName="Book" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> <!-- 忽略列,不生成bean 字段 --> <!-- <ignoreColumn column="FRED" /> --> <!-- 指定列的java数据类型 --> <!-- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> --> </table> </context> </generatorConfiguration>
导入spring-context.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- spring框架与mybatis整合的配置文件加载到spring的上下文中--> <import resource="classpath:spring-mybatis.xml"></import> </beans>
导入spring-mybatis.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://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.xiaoxu及子子孙孙包--> <context:component-scan base-package="com.xiaoxu"/> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!--初始连接数--> <property name="initialSize" value="10"/> <!--最大活动连接数--> <property name="maxTotal" value="100"/> <!--最大空闲连接数--> <property name="maxIdle" value="50"/> <!--最小空闲连接数--> <property name="minIdle" value="10"/> <!--设置为-1时,如果没有可用连接,连接池会一直无限期等待,直到获取到连接为止。--> <!--如果设置为N(毫秒),则连接池会等待N毫秒,等待不到,则抛出异常--> <property name="maxWaitMillis" value="-1"/> </bean> <!--4. spring和MyBatis整合 --> <!--1) 创建sqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 指定数据源 --> <property name="dataSource" ref="dataSource"/> <!-- 自动扫描XxxMapping.xml文件,**任意路径 --> <property name="mapperLocations" value="classpath*:com/xiaoxu/**/mapper/*.xml"/> <!-- 指定别名 --> <property name="typeAliasesPackage" value="com/xiaoxu/**/model"/> <!--配置pagehelper插件--> <property name="plugins"> <array> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <value> helperDialect=mysql </value> </property> </bean> </array> </property> </bean> <!--2) 自动扫描com/xiaoxu/**/mapper下的所有XxxMapper接口(其实就是DAO接口),并实现这些接口,--> <!-- 即可直接在程序中使用dao接口,不用再获取sqlsession对象--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--basePackage 属性是映射器接口文件的包路径。--> <!--你可以使用分号或逗号 作为分隔符设置多于一个的包路径--> <property name="basePackage" value="com/xiaoxu/**/mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> <aop:aspectj-autoproxy/> </beans>
编写接口类:BookBiz
package com.xiaoxu.biz; import com.xiaoxu.model.Book; import com.xiaoxu.utlis.PageBean; import java.util.List; /** * @author小徐 * @site www.veryedu.cn * @company xu集团 * @create 2023-08-25 15:17 */ 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); List<Book> listPage(Book book, PageBean pageBean); }
编写接口实现类:
package com.xiaoxu.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.xiaoxu.biz.BookBiz; import com.xiaoxu.mapper.BookMapper; import com.xiaoxu.model.Book; import com.xiaoxu.utlis.PageBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author小徐 * @site www.veryedu.cn * @company xu集团 * @create 2023-08-25 15:19 */ @Service public class BookBizimpl implements BookBiz { //相当于set,get方法 @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> listPage(Book book, PageBean pageBean) { // if (pageBean !=null && pageBean.isPagination()) // PageHelper.startPage(pageBean.getPage(),pageBean.getRows()); // List<Book> list = bookMapper.listPage(book); // if (pageBean !=null && pageBean.isPagination()){ // PageInfo<Book> info = new PageInfo<>(list); // pageBean.setTotal((int)info.getTotal()); // } return bookMapper.listPage(book); } }
编写实体类:
package com.xiaoxu.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; //@Data @AllArgsConstructor @NoArgsConstructor public class Book { private Integer bid; private String bname; private Float price; public Book(Integer bid, String bname, Float price) { this.bid = bid; this.bname = bname; this.price = price; } public Book() { super(); } public Integer getBid() { return bid; } public void setBid(Integer bid) { this.bid = bid; } public String getBname() { return bname; } public void setBname(String bname) { this.bname = bname; } public Float getPrice() { return price; } public void setPrice(Float price) { this.price = price; } @Override public String toString() { return "Book{" + "bid=" + bid + ", bname='" + bname + '\'' + ", price=" + price + '}'; } }
编写接口测试类:
package com.xiaoxu.impl; import com.xiaoxu.biz.BookBiz; import com.xiaoxu.model.Book; import com.xiaoxu.utlis.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; import static org.junit.Assert.*; /** * @author小徐 * @site www.veryedu.cn * @company xu集团 * @create 2023-08-25 16:04 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:spring-context.xml"}) public class BookBizimplTest { @Autowired private BookBiz bookBiz; @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void deleteByPrimaryKey() { System.out.println(this.bookBiz.deleteByPrimaryKey(1)); } @Test public void insert() { } @Test public void insertSelective() { } @Test public void selectByPrimaryKey() { System.out.println(bookBiz.selectByPrimaryKey(37)); } @Test public void updateByPrimaryKeySelective() { } @Test public void updateByPrimaryKey() { } @Test public void listPage() { Book book = new Book(); PageBean pageBean = new PageBean(); pageBean.setPage(2); pageBean.setRows(20); book.setBname("圣墟"); this.bookBiz.listPage(book,pageBean).forEach(System.out::println); } }
测试结果:
aop整合PageHelper分页插件
编写分页查询
<select id="listPage" resultType="com.xiaoxu.model.Book" parameterType="com.xiaoxu.model.Book" > select <include refid="Base_Column_List" /> from t_mvc_book <where> <if test="bname != null"> and bname like concat('%',#{bname},'%') </if> </where> </select>
编写pagebean
package com.xiaoxu.utlis; 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 + "]"; } }
编写PagerAspect类
package com.xiaoxu.aspect; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.xiaoxu.utlis.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 www.veryedu.cn * @company xu集团 * @create 2023-08-25 17:24 * * * *..*Service.*Pager(..) * *:任意返回值类型 * *..:任意包,不限层级 * *service:以serveice结尾的类/接口 * *page:以page结尾的方法 * ..:任意参数 * 符合上述条件,即为目标类或者目标方法 */ @Aspect//代表当前类为切面类 @Component//代表当前类交给spring进行管理 public class PagerAspect { @Around("execution(* *..*Service.*Pager(..))") public Object invoke(ProceedingJoinPoint args) throws Throwable { PageBean pageBean = null; Object[] params = args.getArgs(); for (Object param : params) { if(param instanceof PageBean){ pageBean = (PageBean)param; break; } } if(pageBean != null && pageBean.isPagination()) PageHelper.startPage(pageBean.getPage(),pageBean.getRows()); Object list = args.proceed(params); if(null != pageBean && pageBean.isPagination()){ PageInfo pageInfo = new PageInfo((List) list); pageBean.setTotal(pageInfo.getTotal()+""); } return list; } }
测试结果