Mybatis根据id查询用户

1.Dao

package com.leo.dao;

import com.leo.pojo.User;

import java.util.List;

public interface UserDao {

    // 查询全部用户
    List<User> getUserList();

    // 根据id查询用户
    User getUserById(int id);
}

2.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.leo.dao.UserDao">
    <select id="getUserList" resultType="com.leo.pojo.User">
        select * from mybatis.user
    </select>
    <select id="getUserById" resultType="com.leo.pojo.User" parameterType="int">
        select * from mybatis.user where id = #{id}
    </select>
</mapper>

3.测试代码

package com.leo.dao;

import com.leo.pojo.User;
import com.leo.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoTest {
    @Test
    public void test() {
        // 获取sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        try {
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            List<User> userList = userDao.getUserList();
            for (User user : userList) {
                System.out.println(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭sqlSession
            sqlSession.close();
        }

    }

    @Test
    public void testGetUserById() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        User user = mapper.getUserById(1);
        System.out.println(user);
        // 关闭sqlSession
        sqlSession.close();
    }
}

4.执行

Mybatis根据id查询用户

上一篇:session和cookie


下一篇:@Controller、@Service和@Repository注解详解