Mybatis搭建步骤

  1. 第一步导入jar包
    Mybatis搭建步骤_第1张图片
    分别是:
    Mybatis搭建步骤_第2张图片
    其中
    在这里插入图片描述
    Mybatis搭建步骤_第3张图片
    在这里插入图片描述
    在这里插入图片描述
  2. 第二步设置SqlMapConfig.xml文件与日志文件

设置SqlMapConfig.xml文件
SqlMapConfig.xml,此文件作为mybatis的全局配置文件,配置了mybatis的运行环境等信息
Mybatis搭建步骤_第4张图片





  
    
      
      
        
        
        
        
      
    
    
  


日志文件
Mybatis搭建步骤_第5张图片

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
  1. 第三步创建pojo
    pojo类作为mybatis进行sql映射使用,通常与数据库表对应
    Mybatis搭建步骤_第6张图片
    Mybatis搭建步骤_第7张图片

  2. 第四步创建sql映射文件
    在这里插入图片描述
    Mybatis搭建步骤_第8张图片




	

  1. 第五步创建测试类,看能找到数据库数据不
    Mybatis搭建步骤_第9张图片
    Mybatis搭建步骤_第10张图片
    能找到,看来配置没问题
  2. 第六步 设置mapper动态代理

编写Mapper接口,由Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。

Mapper接口开发需要遵循以下规范:
1、 Mapper.xml文件中的namespace与mapper接口的类路径相同。
2、 Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
3、 Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql 的parameterType的类型相同
4、 Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同

作用:取代接口与接口的实现类
(虽然mapper动态代理也是接口,但是他不需要实现类,只需写一个查询接口即可甚至)
Mybatis搭建步骤_第11张图片

  1. 第七步,,写个测试类,,看能不能正常运行

用sqlSession的getMapper(。class)方法获取接口实现类
Mybatis搭建步骤_第12张图片

	SqlSession ss;
	@Before
	public void testBefore() throws Exception {
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		ss = sqlSessionFactory.openSession();
	}
	
	@Test
	public void test01() {
		DeptMapper dm = ss.getMapper(DeptMapper.class);
		List list = dm.selectAll();
		
		for (Dept dept : list) {
			System.out.println(dept);
		}
	}

Mybatis搭建步骤_第13张图片

你可能感兴趣的:(Mybatis搭建步骤)