一、整合需要1.1、方法
上一章中的数据
需要sPRing通过单例方式管理SqlsessionFactory
spring和mybatis整合生成代理对象,使用SqlSessionFactory创建SqlSession
(spring和mybatis整合自动完成)
持久层的mapper都需要由spring进行管理
二、创建项目整合环境2.1、创建项目
2.2、数据
db.properties
#数据库配置信息
#驱动
driverClass=com.MySQL.jdbc.Driver
#连接url
jdbcUrl=jdbc:mysql://localhost:3306/mybatis?character=utf8#用户名
user=root
#密码
passWord=root
#连接池中保留的最小连接数
minPoolSize=10#连接池中保留的最大连接数。Default:15maxPoolSize=20#最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default:0maxIdletime=1800#当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default:3acquireIncrement=3#连接池中初始化连接数 应在minPoolSize与maxPoolSize之间取值。默认为3
initialPoolSize=15
2.3、confinguration
<?xmlversion="1.0" encoding="UTF-8"?><!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><!--资源文件--><propertiesresource="db.properties"/><settings><!--开启延时加载--><settingname="lazyLoadingEnabled"value="true"/><!--关闭立即加载--><settingname="aggressiveLazyLoading"value="false"/><!--开启二级缓存--><settingname="cacheEnabled"value="true"/></settings><!--别名--><typeAliases><!--<typeAlias type="com.pb.mybatis.po.User" alias="User"/>--><packagename="com.pb.ssm.po"/></typeAliases><!--配置--><environmentsdefault="development"><environmentid="development"><!--事务--><transactionManagertype="JDBC"/><!--数据源--><dataSourcetype="POOLED"><propertyname="driver"value="${driverClass}"/><propertyname="url"value="${jdbcUrl}"/><propertyname="username"value="${user}"/><propertyname="password"value="${password}"/></dataSource></environment></environments><mappers><packagename="com.pb.ssm.mapper"/></mappers></configuration>
2.4 POJO类与接口
packagecom.pb.ssm.po;importjava.util.Date;/***
* @ClassName: Author
* @Description: TODO(作者)
*@author刘楠
* @date 2015-10-31 下午12:39:33
**/publicclassAuthor {//作者idprivateInteger authorId;//作者姓名privateString authorUserName;//作者密码privateString authorPassword;//作者邮箱privateString authorEmail;//作者介绍privateString authroBio;//注册时间privateDate registerTime;publicInteger getAuthorId() {returnauthorId;
}publicvoidsetAuthorId(Integer authorId) {this.authorId =authorId;
}publicString getAuthorUserName() {returnauthorUserName;
}publicvoidsetAuthorUserName(String authorUserName) {this.authorUserName =authorUserName;
}publicString getAuthorPassword() {returnauthorPassword;
}publicvoidsetAuthorPassword(String authorPassword) {this.authorPassword =authorPassword;
}publicString getAuthorEmail() {returnauthorEmail;
}publicvoidsetAuthorEmail(String authorEmail) {this.authorEmail =authorEmail;
}publicString getAuthroBio() {returnauthroBio;
}publicvoidsetAuthroBio(String authroBio) {this.authroBio =authroBio;
}publicDate getRegisterTime() {returnregisterTime;
}publicvoidsetRegisterTime(Date registerTime) {this.registerTime =registerTime;
}
@OverridepublicString toString() {return"Author [authorId=" + authorId + ", authorUserName="
+ authorUserName + ", authorPassword=" +authorPassword+ ", authorEmail=" + authorEmail + ", authroBio=" +authroBio+ ", registerTime=" + registerTime + "]";
}
}
接口
packagecom.pb.ssm.mapper;importcom.pb.ssm.po.Author;publicinterfaceAuthorMapper {/***
* @Title: findAuthorById
* @Description: TODO(根据id查找)
*@param@paramid
*@param@return设定文件
*@returnAuthor 返回类型
*@throws*/publicAuthor findAuthorById(intid);/***
* @Title: addAuthor
* @Description: TODO(添加)
*@param@paramauthor
*@param@return设定文件
*@returnint 返回类型
*@throws*/publicintaddAuthor(Author author);/***
* @Title: updateAuthor
* @Description: TODO(更新)
*@param@paramauthor
*@param@return设定文件
*@returnint 返回类型
*@throws*/publicintupdateAuthor(Author author);/*** 删除
* @Title: delteAuthor
* @Description: TODO(根据ID删除)
*@param@paramid
*@param@return设定文件
*@returnint 返回类型
*@throws*/publicintdelteAuthor(intid);
}
mapper.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.pb.ssm.mapper.AuthorMapper"><!--开启本mapper下的二级缓冲
type指定为ehcachecache类开
在ehcache和mybatis的整合包中--><cache/><!--映射作者Author--><resultMaptype="Author"id="authorResultMap"><idproperty="authorId"column="author_id"/><resultproperty="authorUserName"column="author_username"/><resultproperty="authorPassword"column="author_password"/><resultproperty="authorEmail"column="author_email"/><resultproperty="authroBio"column="author_bio"/><resultproperty="registerTime"column="register_time"/></resultMap><!--根据ID查找--><selectid="findAuthorById"parameterType="int"resultMap="authorResultMap">select * from author
where author_id=#{id}</select><!--添加--><insertid="addAuthor"parameterType="Author"useGeneratedKeys="true"keyProperty="authorId">INSERT INTO author(author_username,author_password,author_email,author_bio)
VALUES(#{authorUserName},#{authorPassword},#{authorEmail},#{authroBio})</insert><updateid="updateAuthor"parameterType="Author">update author<set><iftest="authorUserName!=null and authorUserName!=''">author_username=#{authorUserName},</if><iftest="authorPassword!=null and authorPassword!=''">author_password=#{authorPassword},</if><iftest="authorEmail!=null and authorEmail!=''">author_email=#{authorEmail},</if><iftest="authroBio!=null and authroBio!=''">author_bio=#{authroBio},</if><iftest="registerTime!=null">register_time=#{registerTime}</if></set>where author_id=#{authorId}</update><!--删除--><deleteid="delteAuthor"parameterType="int">delete from author where author_id=#{authorId}</delete></mapper>
三、使用Mybatis配置文件.xml整合3.1、写applicationContext.xml
<beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd"><!--加载配置文件--><context:property-placeholderlocation="classpath:db.properties"/><!--配置数据源
使用第三方数据源
也可以使用dbcp
或者 spring自带的:org.springframework.jdbc.datasource.DriverManagerDataSource--><beanid="dataSource"class="com.mchange.v2.c3p0.DataSources"destroy-method="close"><!--加载数据库驱动--><propertyname="driverClass"value="${driverClass}"/><!--连接数据库的URL--><propertyname="jdbcUrl"value="#{jdbcUrl}"/><!--连接数据库的用户名和密码--><propertyname="user"value="${user}"/><propertyname="password"value="${password}"/><!--连接池中保留的最小连接数--><propertyname="minPoolSize"value="${minPoolSize}"/><!--连接池中保留的最大连接数--><propertyname="maxPoolSize"value="${maxPoolSize}"/><!--最大空闲时间--><propertyname="maxIdletime"value="${maxIdletime}"/><!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3--><propertyname="acquireIncrement"value="${acquireIncrement}"/><!--连接池中初始化连接数 应在minPoolSize与maxPoolSize之间取值。默认为3--><propertyname="initialPoolSize"value="${initialPoolSize}"/></bean><!--配置SqlSessionFacotry 在mybatis-spring包中--><beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><!--注入数据源 ,将上面的数据源注入--><propertyname="dataSource"ref="dataSource"/>
<!-- 将mybatis的配置文件注入-->
<propertyname="configLocation"value="configuration.xml"/></bean>
3.2、测试
packagecom.pb.ssm.mapper;importjava.io.InputStream;importorg.apache.ibatis.io.Resources;importorg.apache.ibatis.session.SqlSession;importorg.apache.ibatis.session.SqlSessionFactory;importorg.apache.ibatis.session.SqlSessionFactoryBuilder;importorg.junit.Before;importorg.junit.Test;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importcom.pb.ssm.po.Author;publicclassAuthorMapperTest {privateApplicationContext applicationContext;
@BeforepublicvoidsetUp()throwsException {
applicationContext=newClassPathXmlApplicationContext("ApplicationContext.xml");
}
@TestpublicvoidtestFindAuthorById() {
AuthorMapper authorMapper= (AuthorMapper) applicationContext.getBean("authorMapper");
Author author= authorMapper.findAuthorById(2);
System.out.println(author);
}
@TestpublicvoidtestAddAuthor() {//获取会话工厂AuthorMapper authorMapper = (AuthorMapper) applicationContext.getBean("authorMapper");
Author author=newAuthor();
author.setAuthorUserName("程序猿");
author.setAuthorPassword("QWERdlfdad");
author.setAuthorEmail("QWER@QQ.com");intnum =authorMapper.addAuthor(author);
System.out.println("num="+num);
System.out.println("添加后的ID:"+author.getAuthorId());
}
@TestpublicvoidtestUpdateAuthor() {//获取会话工厂AuthorMapper authorMapper = (AuthorMapper) applicationContext.getBean("authorMapper");
Author author= authorMapper.findAuthorById(13);
author.setAuthroBio("天天写代码");
author.setAuthorUserName("码农");intnum=authorMapper.updateAuthor(author);
System.out.println("num="+num);
System.out.println(author);
}
@TestpublicvoidtestDeleteAuthor() {//获取会话工厂AuthorMapper authorMapper = (AuthorMapper) applicationContext.getBean("authorMapper");intnum= authorMapper.delteAuthor(13);
}
}
四、不使用mybatis配置文件4.1、写ApplicationContext.xml
<beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd"><!--开启自动扫描--><!--<context:component-scan base-package="com.pb.ssm"/>--><!--加载配置文件--><context:property-placeholderlocation="db.properties"/><!--配置数据源
使用第三方数据源
也可以使用dbcp
或者 spring自带的:org.springframework.jdbc.datasource.DriverManagerDataSource--><beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource"destroy-method="close"><!--加载数据库驱动--><propertyname="driverClass"value="${driverClass}"/><!--连接数据库的URL--><propertyname="jdbcUrl"value="${jdbcUrl}"/><!--连接数据库的用户名和密码--><propertyname="user"value="${user}"/><propertyname="password"value="${password}"/></bean><!--配置SqlSessionFacotry 在mybatis-spring包中--><beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><!--注入数据源 ,将上面的数据源注入--><propertyname="dataSource"ref="dataSource"/><!--扫描所有Mapper接口的实现类xml 自动扫描mapping.xml文件--><propertyname="mapperLocations"value="classpath:com/pb/ssm/mapping/*.xml"/></bean><!--为所有的Mapper接口注入sqlSessionFactory--><beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer"><!--基本路径 指定扫描的包名--><propertyname="basePackage"value="com.pb.ssm.mapper"/><!--注入sqlSessionFactory--><propertyname="sqlSessionFactoryBeanName"value="sqlSessionFactory"/></bean><!--事务管理--><beanid="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!--注入数据源--><propertyname="dataSource"ref="dataSource"/></bean></beans>
更改Mapper.xml,因为不能使用别名,所以type要写POJO类的全路径
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.pb.ssm.mapper.AuthorMapper"><!--映射作者Author--><resultMaptype="com.pb.ssm.po.Author"id="authorResultMap"><idproperty="authorId"column="author_id"/><resultproperty="authorUserName"column="author_username"/><resultproperty="authorPassword"column="author_password"/><resultproperty="authorEmail"column="author_email"/><resultproperty="authroBio"column="author_bio"/><resultproperty="registerTime"column="register_time"/></resultMap><!--根据ID查找--><selectid="findAuthorById"parameterType="int"resultMap="authorResultMap">select * from author
where author_id=#{id}</select><!--添加--><insertid="addAuthor"parameterType="com.pb.ssm.po.Author"useGeneratedKeys="true"keyProperty="authorId">INSERT INTO author(author_username,author_password,author_email,author_bio)
VALUES(#{authorUserName},#{authorPassword},#{authorEmail},#{authroBio})</insert><updateid="updateAuthor"parameterType="com.pb.ssm.po.Author">update author<set><iftest="authorUserName!=null and authorUserName!=''">author_username=#{authorUserName},</if><iftest="authorPassword!=null and authorPassword!=''">author_password=#{authorPassword},</if><iftest="authorEmail!=null and authorEmail!=''">author_email=#{authorEmail},</if><iftest="authroBio!=null and authroBio!=''">author_bio=#{authroBio},</if><iftest="registerTime!=null">register_time=#{registerTime}</if></set>where author_id=#{authorId}</update><!--删除--><deleteid="delteAuthor"parameterType="int">delete from author where author_id=#{authorId}</delete></mapper>
测试类同上