1.MyBatis的结构
2.MyBatis入门案例
a.创建java项目,并在其中导入相关开发包
b.导入约束文件
http://mybatis.org/dtd/mybatis-3-config.dtd
c.编写配置文件sqlMapConfig.xml,配置文件
d.创建表,创建bean
(1)创建表
-- 创建数据库create database mybatis;-- 创建表use mybatis;create table user ( id int primary key auto_increment, name varchar(255), age int(10));-- 插入数据insert into user values (null,'aaa',19),(null,'bbb',29),(null,'ccc',39),(null,'ddd',22),(null,'eee',33);
(2)创建bean
package cn.tedu.mybatis.beans;public class User { private int id; private String name; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; }}
(3)编写映射文件,描述bean和表sql的映射关系
(4)将映射文件配置到sqlMapConfig.xml中
(5)测试类测试
package cn.tedu.mybatis.test;import java.io.InputStream;import java.util.Arrays;import java.util.List;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.Test;import cn.tedu.mybatis.beans.User;public class MybatisTest { @Test public void test01() throws Exception{ // 1.读取MyBatis核心配置文件 InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml"); // 2.根据配置文件创建sqlSessionFactory SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); // 3.创建sqlSession SqlSession session = factory.openSession(); // 4.执行操作 Listlist = session.selectList("cn.tedu.mybatis.beans.UserMapper.queryAll"); // 5.遍历结果 System.out.println(Arrays.toString(list.toArray())); }}
(6)调用过程