1.创建一个Maven工程
添加Maven依赖
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
</dependencies>
2.创建数据库和表
创建一个mybatis的数据库,以及一个t_dept部门表,建表sql如下:
CREATE TABLE `t_dept` (
`id` int(2) NOT NULL AUTO_INCREMENT COMMENT 'id',
`dept_name` varchar(20) DEFAULT NULL COMMENT '部门名称',
`location` varchar(20) DEFAULT NULL COMMENT '所属地区',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
3.在工程中创建实体类
public class Dept {
private Integer id;
private String deptName;
private String location;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
4.创建sql映射文件
在src/main/resource下创建与当前表对应的SQL映射文件用于声明SQL语句
可以从官网中(ctrl+f搜“namespace”)找到相应的头文件,后面还会细说,这里先拿来引用
DeptMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="Dept">
<insert id="insertDept">
insert into t_dept (id, dept_name, location) values (
#{id}, #{deptName}, #{location}
)
</insert>
</mapper>
5.创建Mybais核心配置文件
在src/main/resources下创建Mybatis-config.xml作为核心配置文件
在刚才给出官网中(ctrl+f搜“environments”)找到相应的头文件
<?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="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8&autoReconnect=true"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="DeptMapper.xml"/>
</mappers>
</configuration>
6.编写测试类,测试sql的执行
public class Test {
public static void main(String[] args) throws IOException {
Dept dept = new Dept();
dept.setDeptName("部门1");
dept.setLocation("北京市");
InputStream is = Resources.getResourceAsStream("Mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = factory.openSession();
session.insert("insertDept", dept);
session.commit();
session.close();
}
}
7.运行sql语句,控制台没有报错,我们再看数据库中,已经插入成功
整个包结构及路径如下
下一节,会分析一下Mybatis的基本调用流程