【工程截图(几个关键的标红框)】
【UserMapper.xml】
【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却忘记加载!
【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()); }}
【运行结果】