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: 3
acquireIncrement=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>

 

測試類同上

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM