01- MyBatis - 根据id查询

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yk10010/article/details/89417944

MyBatis根据id查询用户

使用的SQL:

SELECT * FROM `user`WHERE id = 1

映射文件
在user.xml中添加select标签,编写sql:

<?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">

<!-- namespace:命名空间,用于隔离sql,还有一个很重要的作用,后面会讲 -->

<mapper namespace="test">
	
	<!-- id:statement的id 或者叫做sql的id-->
	<!-- parameterType:声明输入参数的类型 -->
	<!-- resultType:声明输出结果的类型,应该填写pojo的全路径 -->
	<!-- #{}:输入参数的占位符,相当于jdbc的? -->
	
	<select id="queryUserById" parameterType="int"  resultType="cn.itcast.mybatis.pojo.User">
		    SELECT * FROM `user` WHERE id  = #{id}
	</select>
</mapper>

MybatisTest编写测试程序如下:

public class MybatisTest {
    private SqlSessionFactory sqlSessionFactory = null;

    @Before
    public void init() throws Exception {
        // 1. 创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

        // 2. 加载SqlMapConfig.xml配置文件
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");

        // 3. 创建SqlSessionFactory对象
        this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
    }

    @Test
    public void testQueryUserById() throws Exception {
        // 4. 创建SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        // 5. 执行SqlSession对象执行查询,获取结果User
        // 第一个参数是User.xml的statement的id,第二个参数是执行sql需要的参数;
        Object user = sqlSession.selectOne("queryUserById", 1);

        // 6. 打印结果
        System.out.println(user);

        // 7. 释放资源
        sqlSession.close();
    }
}

猜你喜欢

转载自blog.csdn.net/yk10010/article/details/89417944
01-