# MyBatis作为一个ORM框架,其重要程度不用过多介绍。
下面开始一起学习吧:
本博客的编程方法与MyBatis官方文档基本一致:
## 1.创建一个数据库mybatis_learn以及对应的表tbl_employee:
`CREATE DATABASE mybatis_learn;`
```
CREATE TABLE `tbl_employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`last_name` varchar(255) DEFAULT NULL,
`gender` char(1) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
```
## 2.创建一个JavaBean(使用了lombok):
```
package com.mybatis.learn.bean;
import lombok.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Employee {
private Integer id;
private String lastName;
private String gender;
private String email;
}
```
## 3.正式开始玩Mybatis:
### 3.1 引入依赖或者jar包
```
```
### 3.2创建SqlSessionFactory(不/使用xml方式)
使用xml方式:
```
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
```
使用这种方式时,需要你写一个配置文件mybatis-config.xml:
```
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
```
当然, 你也可以告别繁琐的xml文件配置:
```
DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(BlogMapper.class);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
```
###3.3从 SqlSessionFactory 中获取 SqlSession
```
SqlSession session = sqlSessionFactory.openSession();
try {
Employee employee = (Employee) session.selectOne("org.mybatis.example.BlogMapper.selectEmployee", 1);
System.out.println(employee);
} finally {
session.close();
}
```
同时别忘了写具体的sql映射文件:
```
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
select * from tbl_employee where id = #{id}
```
这样子就可以正常查询了(lastName 需要在配置文件中使用别名)