无废话mybatis三(select的用法)

UserMapper.xml




    
        
        
        
        
        
        
        
    

    

    


mapper节点中需要指定namespace="tk.mybatis.simple.mapper.UserMapper"

resultMap:用于设置返回值的类型和映射关系
select * from sys_user where id =#{id}

下面一个是根据设置mybatis的自动映射字段成




BaseMapperTest.java

package simple;

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.BeforeClass;

import java.io.IOException;
import java.io.Reader;

public class BaseMapperTest {
    private static SqlSessionFactory sqlSessionFactory;

    @BeforeClass
    public static void init() {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        } catch (IOException ignore) {
            ignore.printStackTrace();
        }
    }

    public SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}

@Test
    public void testUserSelectById() {
        SqlSession sqlSession = getSqlSession();
        try {
            SysUser sysUser = sqlSession.selectOne("tk.mybatis.simple.mapper.UserMapper.selectByid", 1);
            System.out.println(sysUser.getUserName());
        } finally {
            sqlSession.close();
        }
    }
无废话mybatis三(select的用法)_第3张图片
image.png

在调用的时候是直接指定名称, 当然还有一种不需要指定名称的方式, 那就是getMapper的方式

@Test
    public void testUserSelectById2() {
        SqlSession sqlSession = getSqlSession();
        try {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            SysUser sysUser = userMapper.selectByid(Long.valueOf(1));
            System.out.println(sysUser.getUserName());
        } finally {
            sqlSession.close();
        }
    }

    @Test
    public void testUserSelectAll2() {
        SqlSession sqlSession = getSqlSession();
        try {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            List sysUsers = userMapper.selectAll();
            if (sysUsers != null) {
                for (SysUser user : sysUsers) {
                    System.out.println(user.getUserName());
                }
            }
        } finally {
            sqlSession.close();
        }
    }

你可能感兴趣的:(无废话mybatis三(select的用法))