10_Mybatis开发Dao方法——mapper代理实现

【工程截图(几个关键的标红框)】

【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.Higgin.Mybatis.mapper.UserMapper">
    <select id="findUserById" parameterType="int" resultType="com.Higgin.Mybatis.po.User">
         SELECT * from USER WHERE id=#{id}
     </select>
 </mapper>

【UserMapper.java】

package com.Higgin.Mybatis.mapper;

import com.Higgin.Mybatis.po.User;

public interface UserMapper {
    //根据id查询用户信息
    public User findUserById(int id) throws Exception;
}

【sqlMapperConfig.xml】  

千万不要配置好了UserMapper.xml却忘记加载!

    <!-- 加载映射文件 -->
    <mappers>
        <mapper resource="sqlmap/user.xml"/>
        
        <mapper resource="mapper/UserMapper.xml"/>    <!-- 这里千万不要为忘了加载 -->
    </mappers>

【UserMapperTest.java】

package com.Higgin.Mybatis.mapper.test;

import static org.junit.Assert.*;

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 com.Higgin.Mybatis.mapper.UserMapper;
import com.Higgin.Mybatis.po.User;

public class UserMapperTest {
    
    private SqlSessionFactory sqlSessionFactory ;
    
    @Before
    public void setUp() throws Exception {
        //创建sqlSessionfactory
        //MyBatis配置文件
        String resource="SqlMapConfig.xml";
        //得到配置文件流
        InputStream inputStream=Resources.getResourceAsStream(resource);
        //创建会话工厂,传入MyBatis的配置文件信息
        sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
    public void testFindUserById() throws Exception {
        
        SqlSession sqlSession =sqlSessionFactory.openSession();
        
        //创建一个UserMapper对象,Mybatis自动生成mapper代理对象
      UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        
        //调用userMapper的方法
        User user = userMapper.findUserById(5);
        
        System.out.println(user.toString());
    }

}

【运行结果】

 

posted @ 2016-07-24 12:52  HigginCui  阅读(1144)  评论(0编辑  收藏  举报