Spring : 征服資料庫 (三)

來源:互聯網
上載者:User

標籤:spring   mybatis   

上一篇我們簡單的講解了Spring和MyBatis的整合,但你不難發現,其配置起來還是夠麻煩的。最明顯的一點是,我們需要在自訂的Mapper介面寫個很長的SQL註解,並且還要手動註冊到Spring容器。本文主要講解簡化的方法。


首先,還是定義介面,但你已看不到任何架構的痕迹,

package org.chen.mybatis.mapper;import org.chen.domain.Spitter;public interface SpitterMapper {Spitter getSpitter(String email);}

如果使用的是Maven,在資源檔夾resouces,建立和org.chen.mybatis.mapper相同的目錄結構,


檔案SpitterMapper的名字必須和上面的介面同名。SpitterMapper的內容如下:

<?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="org.chen.mybatis.mapper.SpitterMapper">  <select id="getSpitter" resultType="org.chen.domain.Spitter">    select * from  spitter where email = #{email}  </select></mapper>

id和介面對應的方法名同名,resultType是返回類名。(你可能覺得寫這麼長的類名很麻煩,確實是,等會有簡化的方法)

接下來在Spring設定檔裡,

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">        <property name="basePackage" value="org.chen.mybatis.mapper" />     </bean>

這個bean的作用和自動檢測的一樣,就是自動把basePackage指定的包下的mapper註冊成MyBatis.

為了簡化上面的resultType的書寫,

  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <property name="dataSource" ref="dataSource" />         <property name="typeAliasesPackage" value="org.chen.domain" />  </bean>

添加一個typeAliasesPackage,即包名的別名,這樣直接寫resultType="Spitter"就可以了。

最後我們向service注入Mapper,

@Servicepublic class TestService {@Autowiredprivate SpitterMapper spitterMapper;public void setSpitterMapper(SpitterMapper spitterMapper) {this.spitterMapper = spitterMapper;}


Spring : 征服資料庫 (三)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.