mybatis实践篇(一)—— mybatis入门

本来只是想整理一下mybatis的源码的,不过突然发现很多基础的东西也需要回顾一下了,所以这里就从头开始整理一下mybatis。

Mybatis入门:

1、创建maven工程,引入mybatis相关依赖:

        
        
            org.mybatis
            mybatis
            3.5.0
        
        
        
            mysql
            mysql-connector-java
            5.1.12
        

        
        
            org.projectlombok
            lombok
            1.18.2
            provided
         
        
        
            junit
            junit
            4.12
            test
        

其中mybatis包和mysql驱动包是必须要添加的,而lombok和junit测试包是非必须的。

2、配置mybatis,configuration.xml




    
        
        
            
            
                
                
                
                
            
        
    

     
     
        
    

zsmtest库中存在表man,并有几条测试数据:

mybatis实践篇(一)—— mybatis入门_第1张图片

3、编写mybatis应用代码

(1)Man实体:

import lombok.Data;

@Data
public class Man {

    private String id;

    private String name;

    private String sex;

    private Integer age;

}

(2)ManMapper接口

import org.apache.ibatis.annotations.Param; 

public interface ManMapper {
 
    Man selectMan(@Param("id") String id);
}

(3)ManMapper.xml配置文件






    

注意,我这里使用的事Idea开发,由于Idea下的maven项目默认是不加载src目录下的*.xml文件的,所以需要在maven项目中添加如下配置:

mybatis实践篇(一)—— mybatis入门_第2张图片

否则会提示找不到对应的mapper.xml文件。

4、编写测试类

public class mybatisTest {

    @Test
    public void test() throws IOException {
        
        String resource = "configuration.xml";
        InputStream stream = Resources.getResourceAsStream(resource); 
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(stream);

        SqlSession sqlSession = build.openSession();
        ManMapper mapper = sqlSession.getMapper(ManMapper.class);
        Man man = mapper.selectMan("2");
        System.out.println(man.toString());
    }
}

输出结果:

你可能感兴趣的:(Mybatis,mybatis入门)