Mybatis3.2.1使用例三:Mapper方式整合Spring、設定檔提供SQL

來源:互聯網
上載者:User

上例介紹了使用註解而不需要mybatis設定檔的方式來提供SQL,不過在一個或幾個設定檔中集中管理所有SQL語句也是另外一種便利的方式,下例介紹怎樣使用設定檔來提供SQL語句,同樣還是使用Mapper的方式進行資料庫操作。

(1) 承載資料的User bean:com/mybatis/demo3/User.java

package com.mybatis.demo3;public class User {/** 使用者ID */private int id;/** 使用者名稱稱 */private String name;/** 使用者密碼 */private String password;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}

(2) Mapper介面類:com/mybatis/demo3/UserMapper.java

(只需提供介面方法,應用中mybatis會使用動態反射的方式提供查詢的實際邏輯;該Mapper中沒有通過註解提供所使用的SQL語句,SQL語句挪到設定檔中進行配置)

package com.mybatis.demo3;import org.apache.ibatis.annotations.Param;public interface UserMapper {// 這裡不使用註解,使用的SQL語句來自於設定檔UserMappers.xmlpublic User findByName(@Param("name") String name);}

(3) 資料來源properties檔案:com/mybatis/demo2/mysql.properties

driver=com.mysql.jdbc.Driverurl=jdbc:mysql://127.0.0.1:3306/bookstoreusername=rootpassword=123456

(4) Spring的設定檔:com/mybatis/demo3/applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"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.xsd"><bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations" value="classpath:com/mybatis/demo3/mysql.properties"/></bean><!-- 資料來源 --><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close"><property name="driverClassName" value="${driver}" /><property name="url" value="${url}" /><property name="username" value="${username}" /><property name="password" value="${password}" /></bean><!-- 建立SqlSessionFactory,需指定資料來源,property名稱必須為dataSource --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property  name="configLocation"  value="classpath:com/mybatis/demo3/mybatis_config.xml"/></bean><!--建立資料對應器Mapper,屬性mapperInterface的value必須為介面類--><bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"><property name="mapperInterface" value="com.mybatis.demo3.UserMapper" /><property name="sqlSessionFactory" ref="sqlSessionFactory" /></bean><!-- 資料訪問DAO,在DAO中使用Mapper來查資料 --><bean id="userDao" class="com.mybatis.demo3.UserDaoImpl"><property name="userMapper" ref="userMapper"/></bean></beans>

(5) Mybatis設定檔:com/mybatis/demo3/mybatis_config.xml

(與Spring整合後,該設定檔很多屬性不能用了,比如setting、environment等,主要是使用typeAliases和mappers)

<?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><typeAliases><typeAlias alias="User" type="com.mybatis.demo3.User" /></typeAliases><mappers><mapper resource="com/mybatis/demo3/UserMappers.xml" /></mappers></configuration>

(6) Mapper設定檔:com/mybatis/demo3/UserMappers.xml

(提供SQL的詳細配置,其中select/insert/update/delete語句的id都必須與Mapper的方法名稱相同)

<?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,且值為Mapper的類路徑;直接使用SqlSession時可配可不配 --><mapper namespace="com.mybatis.demo3.UserMapper"><resultMap id="userMap" type="User"><id property="id" column="id" /><result property="name" column="name" /><result property="password" column="password" /></resultMap><select id="findByName" parameterType="String" resultMap="userMap">select * from users where name=#{name}</select></mapper>  

(7) DAO介面:com/mybatis/demo3/UserDao.java

(該介面不是必須有,但在WEB環境中最好能把它介面化使得依賴更小;當然本例並不是WEB環境中使用的,但除了測試類別外都可以直接移植到WEB中)

package com.mybatis.demo3;public interface UserDao {public User getUserByName(String name);}

(8) DAO實作類別:com/mybatis/demo3/UserDaoImpl.java

(通過Spring注入的方式擷取到Mapper,然後使用Mapper進行資料庫操作)

package com.mybatis.demo3;public class UserDaoImpl implements UserDao {/** 該映射器需要與applicationContext.xml中配置的bean屬性一致,並且要用對應的getter/setter */private UserMapper userMapper;@Overridepublic User getUserByName(String name) {return getUserMapper().findByName(name);}public UserMapper getUserMapper() {return userMapper;}public void setUserMapper(UserMapper userMapper) {this.userMapper = userMapper;}}

(9) 測試類別:com/mybatis/demo3/UserManagerPrgm.java

package com.mybatis.demo3;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class UserManagerPrgm {public static void main(String[] args) {String configLocation = "com/mybatis/demo3/applicationContext.xml";ApplicationContext context = new ClassPathXmlApplicationContext(configLocation);UserDao dao = (UserDao)context.getBean("userDao");User user = dao.getUserByName("Joe");System.out.println(user);}}

相比註解的方式,這裡多了一個Mapper.xml設定檔(對於Mybatis的設定檔在使用註解也是可以使用的,主要是提供一個整體的配置),當然Mapper的設定檔可以有多個(建議按模組進行分類以便維護)。該方式的好處是:可以在獨立的設定檔中管理SQL語句。

聯繫我們

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