您好,欢迎访问一九零五行业门户网

MyBatis入门(六)---mybatis与spring的整合

一、整合需要
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: 15 maxpoolsize=20#最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。default: 0 maxidletime=1800#当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。default: 3acquireincrement=3#连接池中初始化连接数 应在minpoolsize与maxpoolsize之间取值。默认为3
initialpoolsize=15
2.3、confinguration
<?xml version="1.0" encoding="utf-8"?><!doctype configuration
public "-//mybatis.org//dtd config 3.0//en"
"http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><!--资源文件 --><properties resource="db.properties"/><settings><!--开启延时加载 --><setting name="lazyloadingenabled" value="true"/><!--关闭立即加载 --><setting name="aggressivelazyloading" value="false"/><!--开启二级缓存 --><setting name="cacheenabled" value="true" /></settings><!-- 别名 --><typealiases><!-- <typealias type="com.pb.mybatis.po.user" alias="user"/> --><package name="com.pb.ssm.po"/></typealiases><!--配置 --><environments default="development"><environment id="development">
   <!--事务 -->
   <transactionmanager type="jdbc"/>
   <!--数据源 -->
   <datasource type="pooled">
   <property name="driver" value="${driverclass}"/>
   <property name="url" value="${jdbcurl}"/>
   <property name="username" value="${user}"/>
   <property name="password" value="${password}"/>
   </datasource></environment></environments><mappers>
   <package name="com.pb.ssm.mapper"/></mappers></configuration>
2.4 pojo类与接口
package com.pb.ssm.po;import java.util.date;/**
*
* @classname: author
* @description: todo(作者)
* @author 刘楠
* @date 2015-10-31 下午12:39:33
* */public class author {    //作者id
   private integer authorid;    //作者姓名
   private string authorusername;    //作者密码
   private string authorpassword;    //作者邮箱
   private string authoremail;    //作者介绍
   private string authrobio;    //注册时间
   private date registertime;
public integer getauthorid() {        return authorid;
   }    public void setauthorid(integer authorid) {        this.authorid = authorid;
   }    public string getauthorusername() {        return authorusername;
   }    public void setauthorusername(string authorusername) {        this.authorusername = authorusername;
   }    public string getauthorpassword() {        return authorpassword;
   }    public void setauthorpassword(string authorpassword) {        this.authorpassword = authorpassword;
   }    public string getauthoremail() {        return authoremail;
   }    public void setauthoremail(string authoremail) {        this.authoremail = authoremail;
   }    public string getauthrobio() {        return authrobio;
   }    public void setauthrobio(string authrobio) {        this.authrobio = authrobio;
   }    public date getregistertime() {        return registertime;
   }    public void setregistertime(date registertime) {        this.registertime = registertime;
   }
   @override    public string tostring() {        return author [authorid= + authorid + , authorusername=
               + authorusername + , authorpassword= + authorpassword                + , authoremail= + authoremail + , authrobio= + authrobio                + , registertime= + registertime + ];
   }
}
接口
package com.pb.ssm.mapper;import com.pb.ssm.po.author;public interface authormapper {    /**
    *
* @title: findauthorbyid
* @description: todo(根据id查找)
* @param @param id
   * @param @return    设定文件
* @return author    返回类型
* @throws
    */
   public author findauthorbyid(int id);    
   /**
    *
* @title: addauthor
* @description: todo(添加)
* @param @param author
   * @param @return    设定文件
* @return int    返回类型
* @throws
    */
   public int addauthor(author author);    /**
    *
* @title: updateauthor
* @description: todo(更新)
* @param @param author
   * @param @return    设定文件
* @return int    返回类型
* @throws
    */
   public int updateauthor(author author);    
   /**
    * 删除
* @title: delteauthor
* @description: todo(根据id删除)
* @param @param id
   * @param @return    设定文件
* @return int    返回类型
* @throws
    */
   public int delteauthor(int id);
}
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"><mapper namespace="com.pb.ssm.mapper.authormapper"><!--开启本mapper下的二级缓冲
type指定为ehcachecache类开
在ehcache和mybatis的整合包中 --><cache /><!--映射作者author --><resultmap type="author" id="authorresultmap"><id property="authorid" column="author_id"/><result property="authorusername" column="author_username"/><result property="authorpassword" column="author_password"/><result property="authoremail" column="author_email"/><result property="authrobio" column="author_bio"/><result property="registertime" column="register_time"/></resultmap><!-- 根据id查找 --><select id="findauthorbyid" parametertype="int" resultmap="authorresultmap">select * from author
where author_id=#{id}</select><!--添加 --><insert id="addauthor" parametertype="author" usegeneratedkeys="true" keyproperty="authorid">insert into author(author_username,author_password,author_email,author_bio)
values(#{authorusername},#{authorpassword},#{authoremail},#{authrobio})</insert><update id="updateauthor" parametertype="author">update author<set><if test="authorusername!=null and authorusername!=''">author_username=#{authorusername},</if><if test="authorpassword!=null and authorpassword!=''">author_password=#{authorpassword},</if><if test="authoremail!=null and authoremail!=''">author_email=#{authoremail},</if><if test="authrobio!=null and authrobio!=''">author_bio=#{authrobio},</if><if test="registertime!=null">register_time=#{registertime}</if></set>where author_id=#{authorid}</update><!--删除 --><delete id="delteauthor" parametertype="int">delete from author where author_id=#{authorid}</delete></mapper>
三、使用mybatis配置文件.xml整合
3.1、写applicationcontext.xml
<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: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-placeholder location="classpath:db.properties"/><!--配置数据源 使用第三方数据源 也可以使用dbcp 或者 spring自带的:org.springframework.jdbc.datasource.drivermanagerdatasource --><bean id="datasource" class="com.mchange.v2.c3p0.datasources" destroy-method="close"><!--加载数据库驱动 --><property name="driverclass" value="${driverclass}"/><!--连接数据库的url --><property name="jdbcurl" value="#{jdbcurl}"/><!--连接数据库的用户名和密码 --><property name="user" value="${user}"/><property name="password" value="${password}"/><!-- 连接池中保留的最小连接数 --><property name="minpoolsize" value="${minpoolsize}"/><!-- 连接池中保留的最大连接数 --><property name="maxpoolsize" value="${maxpoolsize}"/><!-- 最大空闲时间 --><property name="maxidletime" value="${maxidletime}"/><!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。default: 3 --><property name="acquireincrement" value="${acquireincrement}"/><!--连接池中初始化连接数 应在minpoolsize与maxpoolsize之间取值。默认为3--><property name="initialpoolsize" value="${initialpoolsize}"/></bean><!--配置sqlsessionfacotry 在mybatis-spring包中--><bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean"><!--注入数据源 ,将上面的数据源注入--><property name="datasource" ref="datasource" />
<!-- 将mybatis的配置文件注入-->
<property name="configlocation" value="configuration.xml"/></bean>
3.2、测试
package com.pb.ssm.mapper;import java.io.inputstream;import org.apache.ibatis.io.resources;import org.apache.ibatis.session.sqlsession;import org.apache.ibatis.session.sqlsessionfactory;import org.apache.ibatis.session.sqlsessionfactorybuilder;import org.junit.before;import org.junit.test;import org.springframework.context.applicationcontext;import org.springframework.context.support.classpathxmlapplicationcontext;import com.pb.ssm.po.author;public class authormappertest {    private applicationcontext applicationcontext;
@before    public void setup() throws exception {
       applicationcontext=new classpathxmlapplicationcontext(applicationcontext.xml);
   }
@test    public void testfindauthorbyid() {
authormapper authormapper = (authormapper) applicationcontext.getbean(authormapper);
       author author = authormapper.findauthorbyid(2);
       system.out.println(author);
}
@test    public void testaddauthor() {        // 获取会话工厂
       authormapper authormapper = (authormapper) applicationcontext.getbean(authormapper);
author author=new author();
       author.setauthorusername(程序猿);
       author.setauthorpassword(qwerdlfdad);
       author.setauthoremail(qwer@qq.com);
int  num = authormapper.addauthor(author);
system.out.println(num=+num);
       system.out.println(添加后的id:+author.getauthorid());
   }
@test    public void testupdateauthor() {        // 获取会话工厂
       authormapper authormapper = (authormapper) applicationcontext.getbean(authormapper);
       author author = authormapper.findauthorbyid(13);
       author.setauthrobio(天天写代码);
       author.setauthorusername(码农);        int num=authormapper.updateauthor(author);
system.out.println(num=+num);
       system.out.println(author);
   }
@test    public void testdeleteauthor() {        // 获取会话工厂
       authormapper authormapper = (authormapper) applicationcontext.getbean(authormapper);        int num= authormapper.delteauthor(13);
}
}
四、不使用mybatis配置文件
4.1、写applicationcontext.xml
<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: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-placeholder location="db.properties"/><!--配置数据源
使用第三方数据源
也可以使用dbcp
或者 spring自带的:org.springframework.jdbc.datasource.drivermanagerdatasource --><bean id="datasource" class="com.mchange.v2.c3p0.combopooleddatasource" destroy-method="close"><!--加载数据库驱动 --><property name="driverclass" value="${driverclass}"/><!--连接数据库的url --><property name="jdbcurl" value="${jdbcurl}"/><!--连接数据库的用户名和密码 --><property name="user" value="${user}"/><property name="password" value="${password}"/></bean><!--配置sqlsessionfacotry 在mybatis-spring包中--><bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean"><!--注入数据源 ,将上面的数据源注入--><property name="datasource" ref="datasource"/><!-- 扫描所有mapper接口的实现类xml 自动扫描mapping.xml文件 --><property name="mapperlocations" value="classpath:com/pb/ssm/mapping/*.xml"/></bean><!--为所有的mapper接口注入sqlsessionfactory --><bean class="org.mybatis.spring.mapper.mapperscannerconfigurer"><!--基本路径 指定扫描的包名 --><property name="basepackage" value="com.pb.ssm.mapper"/><!-- 注入sqlsessionfactory --><property name="sqlsessionfactorybeanname" value="sqlsessionfactory"/></bean><!--事务管理 -->
<bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager"><!-- 注入数据源 --><property name="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"><mapper namespace="com.pb.ssm.mapper.authormapper"><!--映射作者author --><resultmap type="com.pb.ssm.po.author" id="authorresultmap"><id property="authorid" column="author_id"/><result property="authorusername" column="author_username"/><result property="authorpassword" column="author_password"/><result property="authoremail" column="author_email"/><result property="authrobio" column="author_bio"/><result property="registertime" column="register_time"/></resultmap><!-- 根据id查找 --><select id="findauthorbyid" parametertype="int" resultmap="authorresultmap">select * from author
where author_id=#{id}</select><!--添加 --><insert id="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><update id="updateauthor" parametertype="com.pb.ssm.po.author">update author<set><if test="authorusername!=null and authorusername!=''">author_username=#{authorusername},</if><if test="authorpassword!=null and authorpassword!=''">author_password=#{authorpassword},</if><if test="authoremail!=null and authoremail!=''">author_email=#{authoremail},</if><if test="authrobio!=null and authrobio!=''">author_bio=#{authrobio},</if><if test="registertime!=null">register_time=#{registertime}</if></set>where author_id=#{authorid}</update><!--删除 --><delete id="delteauthor" parametertype="int">delete from author where author_id=#{authorid}</delete></mapper>
测试类同上
 以上就是mybatis入门(六)---mybatis与spring的整合的内容。
其它类似信息

推荐信息