Mybatis与spring集成
1、导入pom依赖
1.1 添加spring相关依赖(5.0.2.RELEASE)
spring-core
spring-beans
spring-context
spring-orm
spring-tx
spring-aspects
spring-web
1.2 添加mybatis相关依赖
mybatis核心:mybatis(3.4.5)
Mybatis分页:pagehelper(5.1.2)
1.3 spring整合mybatis(1.3.1)
mybatis-spring
1.4 添加dbcp2连接池
commons-dbcp2(2.1.1)
commons-pool2(2.4.3)
1.5 添加日志配置(2.9.1)
log4j-core
log4j-api
log4j-web
1.6 其他
junit(4.12)
javax.servlet-api(4.0.0)
lombok(1.18.2)
注:使用mybatis-generator插件,pom文件添加支持
pom.xml依赖
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>com.yuan</groupId> 8 <artifactId>ssm</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 <packaging>war</packaging> 11 12 <name>ssm Maven Webapp</name> 13 <!-- FIXME change it to the project's website --> 14 <url>http://www.example.com</url> 15 16 <properties> 17 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 18 <maven.compiler.source>1.8</maven.compiler.source> 19 <maven.compiler.target>1.8</maven.compiler.target> 20 <maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version> 21 22 <!--添加jar包依赖--> 23 <!--1.spring 5.0.2.RELEASE相关--> 24 <spring.version>5.0.2.RELEASE</spring.version> 25 <!--2.mybatis相关--> 26 <mybatis.version>3.4.5</mybatis.version> 27 <!--mysql--> 28 <mysql.version>5.1.44</mysql.version> 29 <!--pagehelper分页jar依赖--> 30 <pagehelper.version>5.1.2</pagehelper.version> 31 <!--mybatis与spring集成jar依赖--> 32 <mybatis.spring.version>1.3.1</mybatis.spring.version> 33 <!--3.dbcp2连接池相关 druid--> 34 <commons.dbcp2.version>2.1.1</commons.dbcp2.version> 35 <commons.pool2.version>2.4.3</commons.pool2.version> 36 <!--4.log日志相关--> 37 <log4j2.version>2.9.1</log4j2.version> 38 <!--5.其他--> 39 <junit.version>4.12</junit.version> 40 <servlet.version>4.0.0</servlet.version> 41 <lombok.version>1.18.2</lombok.version> 42 </properties> 43 44 45 <dependencies> 46 <!--1.spring相关--> 47 <dependency> 48 <groupId>org.springframework</groupId> 49 <artifactId>spring-context</artifactId> 50 <version>${spring.version}</version> 51 </dependency> 52 <dependency> 53 <groupId>org.springframework</groupId> 54 <artifactId>spring-orm</artifactId> 55 <version>${spring.version}</version> 56 </dependency> 57 <dependency> 58 <groupId>org.springframework</groupId> 59 <artifactId>spring-tx</artifactId> 60 <version>${spring.version}</version> 61 </dependency> 62 <dependency> 63 <groupId>org.springframework</groupId> 64 <artifactId>spring-aspects</artifactId> 65 <version>${spring.version}</version> 66 </dependency> 67 <dependency> 68 <groupId>org.springframework</groupId> 69 <artifactId>spring-web</artifactId> 70 <version>${spring.version}</version> 71 </dependency> 72 <dependency> 73 <groupId>org.springframework</groupId> 74 <artifactId>spring-test</artifactId> 75 <version>${spring.version}</version> 76 </dependency> 77 <!--2.mybatis相关--> 78 <dependency> 79 <groupId>org.mybatis</groupId> 80 <artifactId>mybatis</artifactId> 81 <version>${mybatis.version}</version> 82 </dependency> 83 <!--mysql--> 84 <dependency> 85 <groupId>mysql</groupId> 86 <artifactId>mysql-connector-java</artifactId> 87 <version>${mysql.version}</version> 88 </dependency> 89 <!--pagehelper分页插件jar包依赖--> 90 <dependency> 91 <groupId>com.github.pagehelper</groupId> 92 <artifactId>pagehelper</artifactId> 93 <version>${pagehelper.version}</version> 94 </dependency> 95 <!--mybatis与spring集成jar包依赖--> 96 <dependency> 97 <groupId>org.mybatis</groupId> 98 <artifactId>mybatis-spring</artifactId> 99 <version>${mybatis.spring.version}</version> 100 </dependency> 101 <!--3.dbcp2连接池相关--> 102 <dependency> 103 <groupId>org.apache.commons</groupId> 104 <artifactId>commons-dbcp2</artifactId> 105 <version>${commons.dbcp2.version}</version> 106 </dependency> 107 <dependency> 108 <groupId>org.apache.commons</groupId> 109 <artifactId>commons-pool2</artifactId> 110 <version>${commons.pool2.version}</version> 111 </dependency> 112 <!--4.log日志相关依赖--> 113 <!--核心log4j2jar包--> 114 <dependency> 115 <groupId>org.apache.logging.log4j</groupId> 116 <artifactId>log4j-core</artifactId> 117 <version>${log4j2.version}</version> 118 </dependency> 119 <dependency> 120 <groupId>org.apache.logging.log4j</groupId> 121 <artifactId>log4j-api</artifactId> 122 <version>${log4j2.version}</version> 123 </dependency> 124 <!--web工程需要包含log4j-web,非web工程不需要--> 125 <dependency> 126 <groupId>org.apache.logging.log4j</groupId> 127 <artifactId>log4j-web</artifactId> 128 <version>${log4j2.version}</version> 129 </dependency> 130 <!--5.其他--> 131 <dependency> 132 <groupId>junit</groupId> 133 <artifactId>junit</artifactId> 134 <version>${junit.version}</version> 135 <scope>test</scope> 136 </dependency> 137 <dependency> 138 <groupId>javax.servlet</groupId> 139 <artifactId>javax.servlet-api</artifactId> 140 <version>${servlet.version}</version> 141 <scope>provided</scope> 142 </dependency> 143 <dependency> 144 <groupId>org.projectlombok</groupId> 145 <artifactId>lombok</artifactId> 146 <version>${lombok.version}</version> 147 <scope>provided</scope> 148 </dependency> 149 150 151 152 153 154 155 </dependencies> 156 157 <build> 158 <finalName>ssm</finalName> 159 <resources> 160 <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题--> 161 <resource> 162 <directory>src/main/java</directory> 163 <includes> 164 <include>**/*.xml</include> 165 </includes> 166 </resource> 167 <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题--> 168 <resource> 169 <directory>src/main/resources</directory> 170 <includes> 171 <include>jdbc.properties</include> 172 <include>*.xml</include> 173 </includes> 174 </resource> 175 </resources> 176 177 178 <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> 179 <plugins> 180 <plugin> 181 <groupId>org.apache.maven.plugins</groupId> 182 <artifactId>maven-compiler-plugin</artifactId> 183 <version>${maven.compiler.plugin.version}</version> 184 <configuration> 185 <source>${maven.compiler.source}</source> 186 <target>${maven.compiler.target}</target> 187 <encoding>${project.build.sourceEncoding}</encoding> 188 </configuration> 189 </plugin> 190 <plugin> 191 <groupId>org.mybatis.generator</groupId> 192 <artifactId>mybatis-generator-maven-plugin</artifactId> 193 <version>1.3.2</version> 194 <dependencies> 195 <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 --> 196 <dependency> 197 <groupId>mysql</groupId> 198 <artifactId>mysql-connector-java</artifactId> 199 <version>${mysql.version}</version> 200 </dependency> 201 </dependencies> 202 <configuration> 203 <overwrite>true</overwrite> 204 </configuration> 205 </plugin> 206 207 208 <plugin> 209 <artifactId>maven-clean-plugin</artifactId> 210 <version>3.1.0</version> 211 </plugin> 212 <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> 213 <plugin> 214 <artifactId>maven-resources-plugin</artifactId> 215 <version>3.0.2</version> 216 </plugin> 217 <plugin> 218 <artifactId>maven-compiler-plugin</artifactId> 219 <version>3.8.0</version> 220 </plugin> 221 <plugin> 222 <artifactId>maven-surefire-plugin</artifactId> 223 <version>2.22.1</version> 224 </plugin> 225 <plugin> 226 <artifactId>maven-war-plugin</artifactId> 227 <version>3.2.2</version> 228 </plugin> 229 <plugin> 230 <artifactId>maven-install-plugin</artifactId> 231 <version>2.5.2</version> 232 </plugin> 233 <plugin> 234 <artifactId>maven-deploy-plugin</artifactId> 235 <version>2.8.2</version> 236 </plugin> 237 </plugins> 238 </pluginManagement> 239 </build> 240 </project>
2、利用mybatis逆向工程生成模型层层代码
3、编写配置文件 applicationContext-mybatis.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 5 xmlns:aop="http://www.springframework.org/schema/aop" 6 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"> 7 8 9 <!--1. 注解式开发 --> 10 <!-- 注解驱动 --> 11 <context:annotation-config/> 12 <!-- 用注解方式注入bean,并指定查找范围:com.yuan.ssm及子子孙孙包--> 13 <context:component-scan base-package="com.yuan"/> 14 15 <context:property-placeholder location="classpath:jdbc.properties"/> 16 17 <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" 18 destroy-method="close"> 19 <property name="driverClassName" value="${jdbc.driver}"/> 20 <property name="url" value="${jdbc.url}"/> 21 <property name="username" value="${jdbc.username}"/> 22 <property name="password" value="${jdbc.password}"/> 23 <!--初始连接数--> 24 <property name="initialSize" value="10"/> 25 <!--最大活动连接数--> 26 <property name="maxTotal" value="100"/> 27 <!--最大空闲连接数--> 28 <property name="maxIdle" value="50"/> 29 <!--最小空闲连接数--> 30 <property name="minIdle" value="10"/> 31 <!--设置为-1时,如果没有可用连接,连接池会一直无限期等待,直到获取到连接为止。--> 32 <!--如果设置为N(毫秒),则连接池会等待N毫秒,等待不到,则抛出异常--> 33 <property name="maxWaitMillis" value="-1"/> 34 </bean> 35 36 <!--4. spring和MyBatis整合 --> 37 <!--1) 创建sqlSessionFactory--> 38 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 39 <!-- 指定数据源 --> 40 <property name="dataSource" ref="dataSource"/> 41 <!-- 自动扫描XxxMapping.xml文件,**任意路径 --> 42 <property name="mapperLocations" value="classpath*:com/yuan/**/mapper/*.xml"/> 43 <!-- 指定别名 --> 44 <property name="typeAliasesPackage" value="com/yuan/**/model"/> 45 <!--配置pagehelper插件--> 46 <property name="plugins"> 47 <array> 48 <bean class="com.github.pagehelper.PageInterceptor"> 49 <property name="properties"> 50 <value> 51 helperDialect=mysql 52 </value> 53 </property> 54 </bean> 55 </array> 56 </property> 57 </bean> 58 59 <!--2) 自动扫描com/yuan/ssm/**/mapper下的所有XxxMapper接口(其实就是DAO接口),并实现这些接口,--> 60 <!-- 即可直接在程序中使用dao接口,不用再获取sqlsession对象--> 61 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 62 <!--basePackage 属性是映射器接口文件的包路径。--> 63 <!--你可以使用分号或逗号 作为分隔符设置多于一个的包路径--> 64 <property name="basePackage" value="com/yuan/**/mapper"/> 65 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> 66 </bean> 67 68 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 69 <property name="dataSource" ref="dataSource" /> 70 </bean> 71 <tx:annotation-driven transaction-manager="transactionManager" /> 72 <aop:aspectj-autoproxy/> 73 74 75 </beans>
编写配置文件applicationContext.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 5 6 <!--整合mybatis框架--> 7 <import resource="applicationContext-mybatis.xml"></import> 8 </beans>
Spring Test+junit完美组合
在工程中的pom文件增加spring-test的依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency>
创建SpringBaseTest,并加上以下两个注解
1 package com.yuan; 2 3 import com.yuan.model.Book; 4 import com.yuan.util.PageBean; 5 import org.junit.Before; 6 import org.junit.runner.RunWith; 7 import org.springframework.test.context.ContextConfiguration; 8 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 9 10 @RunWith(SpringJUnit4ClassRunner.class) 11 @ContextConfiguration(locations={"classpath:applicationContext.xml"}) 12 public class SpringBaseTest { 13 14 protected Book book; 15 protected PageBean pageBean; 16 17 @Before 18 public void init(){ 19 book = new Book(); 20 pageBean = new PageBean(); 21 } 22 23 }
相关层Service代码
BookService.java
1 package com.yuan.service; 2 3 import com.yuan.model.Book; 4 import com.yuan.util.PageBean; 5 import org.springframework.stereotype.Service; 6 7 import java.util.List; 8 9 10 public interface BookService { 11 12 int deleteByPrimaryKey(Integer bid); 13 14 int insert(Book record); 15 16 int insertSelective(Book record); 17 18 Book selectByPrimaryKey(Integer bid); 19 20 int updateByPrimaryKeySelective(Book record); 21 22 int updateByPrimaryKey(Book record); 23 24 List<Book> listPager(Book book, PageBean pageBean); 25 }
BookServiceImpl.java
1 package com.yuan.service.impl; 2 3 import com.yuan.mapper.BookMapper; 4 import com.yuan.model.Book; 5 import com.yuan.service.BookService; 6 import com.yuan.util.PageBean; 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.stereotype.Service; 9 10 import java.util.List; 11 12 @Service 13 public class BookServiceImpl implements BookService { 14 @Autowired 15 private BookMapper bookMapper; 16 17 @Override 18 public int deleteByPrimaryKey(Integer bid) { 19 return bookMapper.deleteByPrimaryKey(bid); 20 } 21 22 @Override 23 public int insert(Book record) { 24 return bookMapper.insert(record); 25 } 26 27 @Override 28 public int insertSelective(Book record) { 29 return bookMapper.insertSelective(record); 30 } 31 32 @Override 33 public Book selectByPrimaryKey(Integer bid) { 34 return bookMapper.selectByPrimaryKey(bid); 35 } 36 37 @Override 38 public int updateByPrimaryKeySelective(Book record) { 39 return bookMapper.updateByPrimaryKeySelective(record); 40 } 41 42 @Override 43 public int updateByPrimaryKey(Book record) { 44 return bookMapper.updateByPrimaryKey(record); 45 } 46 47 @Override 48 public List<Book> listPager(Book book, PageBean pageBean) { 49 return bookMapper.listPager(book); 50 } 51 }
测试层BookServiceImplTest.java
1 package com.yuan.service.impl; 2 3 import com.yuan.SpringBaseTest; 4 import com.yuan.model.Book; 5 import com.yuan.service.BookService; 6 import com.yuan.util.PageBean; 7 import com.yuan.util.StringUtil; 8 import org.junit.Test; 9 import org.junit.runner.RunWith; 10 import org.springframework.beans.factory.annotation.Autowired; 11 12 import java.util.List; 13 14 import static org.junit.Assert.*; 15 16 public class BookServiceImplTest extends SpringBaseTest { 17 18 @Autowired 19 private BookService bookService; 20 21 /** 22 * 新增 23 */ 24 @Test 25 public void insert() { 26 book.setBid(2); 27 book.setBname("T226 ssm"); 28 book.setPrice(996f); 29 this.bookService.insert(book); 30 31 } 32 33 /** 34 * 查询 35 */ 36 @Test 37 public void selectByPrimaryKey() { 38 Book book = this.bookService.selectByPrimaryKey(2); 39 System.out.println(book); 40 } 41 42 /** 43 * 删除 44 */ 45 @Test 46 public void deleteByPrimaryKey() { 47 bookService.deleteByPrimaryKey(2); 48 } 49 50 /** 51 * 分页优化 52 */ 53 @Test 54 public void listPager() { 55 Book book = new Book(); 56 //带条件分页查询 57 book.setBname(StringUtil.toLikeStr("圣墟")); 58 PageBean pageBean = new PageBean(); 59 //不分页 60 // pageBean.setPagination(false); 61 //根据页码分页查询 62 pageBean.setPage(2); 63 List<Book> books = bookService.listPager(book, pageBean); 64 for (Book b : books) { 65 System.out.println(b); 66 } 67 } 68 69 }
插入成功
查询结果
删除结果
Aop整合pagehelper插件
注意:记得开动态代理
使用AOP编程解决分页代码重复的问题
@Around("execution(* *..*Service.*pager(..))")
public Object invoke(ProceedingJoinPoint args)
语法结构:execution(方法修饰符 方法返回值 方法所属类 匹配方法名 ( 方法中的形参表 ) 方法申明抛出的异常 )
"*" :代表一个任意类型的参数;
“..”:代表零个或多个任意类型的参数。
案例:
PageAspect.java
1 package com.yuan.component; 2 3 import com.github.pagehelper.PageHelper; 4 import com.github.pagehelper.PageInfo; 5 import com.yuan.util.PageBean; 6 import org.aspectj.lang.ProceedingJoinPoint; 7 import org.aspectj.lang.annotation.Around; 8 import org.aspectj.lang.annotation.Aspect; 9 import org.springframework.stereotype.Component; 10 11 import java.util.List; 12 13 @Component 14 @Aspect 15 public class PagerAspect { 16 17 @Around("execution(* *..*Service.*Pager(..))") 18 public Object invoke(ProceedingJoinPoint args)throws Throwable{ 19 //符合*..*Service.*Pager(..)规则的方法,调用时所携带的参数 20 Object[] params = args.getArgs(); 21 PageBean pageBean = null; 22 for (Object param : params) { 23 if(param instanceof PageBean){ 24 pageBean = (PageBean)param; 25 break; 26 } 27 } 28 29 if(pageBean!=null && pageBean.isPagination()){ 30 PageHelper.startPage(pageBean.getPage(),pageBean.getRows()); 31 } 32 33 Object list = args.proceed(params); 34 if(pageBean!=null && pageBean.isPagination()){ 35 PageInfo pageInfo = new PageInfo((List) list); 36 pageBean.setTotal(pageInfo.getTotal()+""); 37 } 38 39 return list; 40 } 41 42 43 }
Bookmapper.java
1 package com.yuan.mapper; 2 3 import com.yuan.model.Book; 4 import org.springframework.stereotype.Repository; 5 6 import java.util.List; 7 8 @Repository 9 public interface BookMapper { 10 int deleteByPrimaryKey(Integer bid); 11 12 int insert(Book record); 13 14 int insertSelective(Book record); 15 16 Book selectByPrimaryKey(Integer bid); 17 18 int updateByPrimaryKeySelective(Book record); 19 20 int updateByPrimaryKey(Book record); 21 22 List<Book> listPager(Book book); 23 24 }
BookMapper.xml
<select id="listPager" resultType="com.yuan.model.Book" parameterType="com.yuan.model.Book"> select <include refid="Base_Column_List"/> from t_mvc_book <where> <if test="bname != null and bname !=''"> bname like #{bname} </if> </where> </select>
service层
1 package com.yuan.service; 2 3 import com.yuan.model.Book; 4 import com.yuan.util.PageBean; 5 import org.springframework.stereotype.Service; 6 7 import java.util.List; 8 9 10 public interface BookService { 11 12 13 List<Book> listPager(Book book, PageBean pageBean); 14 }
测试层代码
1 /** 2 * 分页优化 3 */ 4 @Test 5 public void listPager() { 6 Book book = new Book(); 7 //带条件分页查询 8 book.setBname(StringUtil.toLikeStr("圣墟")); 9 PageBean pageBean = new PageBean(); 10 //不分页 11 // pageBean.setPagination(false); 12 //根据页码分页查询 13 pageBean.setPage(2); 14 List<Book> books = bookService.listPager(book, pageBean); 15 for (Book b : books) { 16 System.out.println(b); 17 } 18 }
不带条件分页查询
带条件分页查询