<?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"> <!-- 这个用来指定对应的dao接口 --> <mapper namespace="com.atguigu.mapper.UserMapper"> <!-- <select>:定义查询语句 id:设置SQL语句的唯一标示 resultType:结果类型,即实体类的全限定名 resultType如果在sqlMapConfig.xml中配置过typeAlisas,则按起的别名来,不建议 --> <select id="getUserByUid" resultType="com.atguigu.bean.User"> select uid,username,password,age,sex from user where uid = ${value} </select> </mapper>
package com.atguigu.mapper; import com.atguigu.bean.User; public interface UserMapper { //和UserMapper.xml中的sql的id对应的 /** * <!-- <select>:定义查询语句 id:设置SQL语句的唯一标示 resultType:结果类型,即实体类的全限定名 --> <select id="getUserByUid" resultType="com.atguigu.bean.User"> select uid,username,password,age,sex from user where uid = ${value} 或者#{id} </select> * @param uid * @return */ User getUserByUid(String uid); }
package com.atguigu.mapper; import static org.junit.Assert.*; import java.io.IOException; import java.io.InputStream; import java.util.Properties; 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.Test; import com.atguigu.bean.User; public class TestMybatis { @Test public void test() throws IOException { InputStream is = Resources.getResourceAsStream("mybatis-config.xml");//org.apache.ibatis.io.Resources //InputStream is = TestMybatis.class.getClassLoader().getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(); //getMapper():会通过动态代理动态生成UserMapper的代理实现类 UserMapper mapper = sqlSession.getMapper(UserMapper.class); System.out.println(mapper.getClass().getName());//com.sun.proxy.$Proxy4这个为生成的代理对象 User user = mapper.getUserByUid("1"); System.out.println(user); //user_name ---> userName } }
转载于:https://www.cnblogs.com/zmy-520131499/p/11397680.html