1. 程式人生 > >MyBatis的動態代理開發

MyBatis的動態代理開發

1 動態代理Dao開發規則

  1. namespace必需是介面的全路徑名
  2. 介面的方法名必需與對映檔案的sql id一致
  3. 介面的輸入引數必需與對映檔案的parameterType型別一致
  4. 介面的返回型別必須與對映檔案的resultType型別一致

 

  • 也就是說有一個UserMapper介面,他的一個方法的名為getUserById,方法的入參為int,返回值為User
public interface UserMapper{
    User getUserById(Integer id)
}

2 開發示例

2.1 建立UserMapper.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.itykd.mapper.UserMapper">
    <select id="getUserById" parameterType="Integer" resultType="com.itykd.domain.User">
        select * from `user` where id=#{id}
    </select>
</mapper>

2.2 建立UserMapper介面

public interface UserMapper{
    User getUserById(Integer id)
}

2.3 在核心配置檔案SqlMapConfig.xml引入UserMapper.xml

    <!-- 載入對映檔案 -->
    <mappers>
        <mapper resource="Mapper/UserMapper.xml"/>
    <mappers>

2.4 測試

package com.itykd.mapper;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import com.itykd.domain.User;
import com.itykd.util.MyBatisUtils;

public class UserMapperTest {

	@Test
	public void testGetUserById() {
		SqlSession sqlSession = MyBatisUtils.getSqlSessionFactory().openSession();
		//獲取介面的代理實現類
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		
		User user = userMapper.getUserById(33);
		System.out.println(user);
		sqlSession.close();
	}
}