1.MyBatis的结构
2.MyBatis入门案例
a.创建java项目,并在其中导入相关开发包
b.导入约束文件
http://mybatis.org/dtd/mybatis-3-config.dtd
c.编写配置文件sqlMapConfig.xml,配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 配置数据源 --> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> </configuration>
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的映射关系
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <mapper namespace="cn.tedu.mybatis.beans.UserMapper"> <select id="queryAll" resultType="cn.tedu.mybatis.beans.User"> select * from user </select> </mapper>
(4)将映射文件配置到sqlMapConfig.xml中
<!-- 声明映射文件 --> <mappers> <mapper resource="cn/tedu/mybatis/beans/UserMapper.xml"/> </mappers>
(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.执行操作 List<User> list = session.selectList("cn.tedu.mybatis.beans.UserMapper.queryAll"); // 5.遍历结果 System.out.println(Arrays.toString(list.toArray())); } }
(6)调用过程