spring整合mybatis之mapper開發

來源:互聯網
上載者:User

標籤:frame   五步   actor   throw   drive   eth   cte   pass   編寫   

1.1    整合思路

1、SqlSessionFactory對象應該放到spring容器中作為單例存在。

2、傳統dao的開發方式中,應該從spring容器中獲得sqlsession對象。

3、Mapper代理形式中,應該從spring容器中直接獲得mapper的代理對象。

4、資料庫的串連以及資料庫連接池交易管理都交給spring容器來完成。

1.2   整合需要的jar包

1、spring的jar包

2、Mybatis的jar包

3、Spring+mybatis的整合包。

4、Mysql的資料庫驅動jar包。

5、資料庫連接池的jar包。

還有一個spring-test的測試包(spring-test\4.1.1.RELEASE)

 1.3   整合的步驟

第一步:建立一個java工程。

第二步:匯入jar包。(上面提到的jar包)

第三步:mybatis的設定檔sqlmapConfig.xml

第四步:編寫Spring的設定檔

1、資料庫連接及串連池

2、交易管理(暫時可以不配置)

3、sqlsessionFactory對象,配置到spring容器中

4、mapeer代理對象或者是dao實作類別配置到spring容器中。

第五步:編寫dao或者mapper檔案

第六步:測試。

 包結構:

1.3.1 SqlMapConfig.xml

原先在sqlMapConfig.xml中的配置都交由spring管理(除了別名,spring不能處理)

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <!-- 配置pojo別名 -->    <typeAliases>        <!-- 包掃描,預設別名是類名,不區分大小寫 -->        <package name="com.mybatis.po"/>    </typeAliases></configuration>
1.3.2applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"    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-4.0.xsd    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">    <!-- 載入設定檔 -->    <context:property-placeholder location="classpath:db.properties" />    <!-- 資料庫連接池 -->    <bean id="dataSource" class="org.apache.commons.dbcp.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="maxActive" value="10" />        <property name="maxIdle" value="5" />    </bean>    <!-- mapper配置 -->    <!-- 讓spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <!-- 資料庫連接池 -->        <property name="dataSource" ref="dataSource" />        <!-- 載入mybatis的全域設定檔 -->        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />    </bean>        <!-- 使用掃描包的形式來建立mapper代理對象 -->    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">        <property name="basePackage" value="com.mybatis.mapper.UserMapper"></property>    </bean></beans>
1.3.3  db.properties
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8jdbc.username=rootjdbc.password=123
1.4 UserMapper.java類
package com.mybatis.mapper;import java.util.List;import com.mybatis.po.User;public interface UserMapper {    //根據使用者id查詢使用者資訊    public User findUserById(int id) throws Exception;    //查詢使用者列表    public List<User> findUserByUsername(String username) throws Exception;    //添加使用者資訊    public void insertUser(User user)throws Exception; }
1.5 UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.mybatis.mapper.UserMapper"><!-- 根據id擷取使用者資訊 -->    <select id="findUserById" parameterType="int" resultType="user">        select * from user where id = #{id}    </select><!-- 自訂條件查詢使用者列表 -->    <select id="findUserByUsername" parameterType="java.lang.String"             resultType="user">       select * from user where username like ‘%${value}%‘     </select><!-- 添加使用者 -->    <insert id="insertUser" parameterType="user">    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">        select LAST_INSERT_ID()     </selectKey>      insert into user(username,birthday,sex,address)       values(#{username},#{birthday},#{sex},#{address})    </insert></mapper>
1.6 掃描包形式配置mapper
<!-- 使用掃描包的形式來建立mapper代理對象 -->    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">        <property name="basePackage" value="com.mybatis.mapper"></property>    </bean>

每個mapper代理對象的id就是類名,首字母小寫,多個包之間使用“,”間隔。

1.7   測試方法
package test;import static org.junit.Assert.*;import java.util.Date;import java.util.List;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 com.mybatis.mapper.UserMapper;import com.mybatis.po.User;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations="classpath:spring/applicationContext.xml")public class UserMapperTest {        @Autowired    private UserMapper userMapper;    @Test    public void testFindUserById() throws Exception {        User user = userMapper.findUserById(10);        System.out.println(user);    }    @Test    public void testFindUserByUsername() throws Exception {        List<User> list = userMapper.findUserByUsername("%張%");        for (User user : list) {            System.out.println(user);        }    }    @Test    public void testInsertUser() throws Exception {        User user = new User();        user.setAddress("北京");        user.setBirthday(new Date());        user.setSex("2");        user.setUsername("韓美美");        userMapper.insertUser(user);    }}

 

spring整合mybatis之mapper開發

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.