MyBatis-01:環境搭建
阿新 • • 發佈:2020-12-05
# MyBatis-01:環境搭建
### 1.搭建實驗資料庫
```mysql
CREATE DATABASE `mybatis`;
USE `mybatis`;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(20) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`pwd` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `user`(`id`,`name`,`pwd`) values (1,'狂神','123456'),(2,'張三','abcdef'),(3,'李四','987654');
```
### 2.匯入 Maven 相關依賴
```xml
org.mybatis
mybatis
3.5.2
mysql
mysql-connector-java
5.1.47
```
### 3.編寫 MyBatis 核心配置檔案
可以根據幫助文件來進行編寫
[Mybatis幫助文件]: https://mybatis.org/mybatis-3/zh/index.html
```xml
```
### 4.編寫 MyBatis 工具類
```java
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 java.io.IOException;
import java.io.InputStream;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//獲取SqlSession連線
public static SqlSession getSession(){
return sqlSessionFactory.openSession();
}
}
```
### 5.建立實體類
```java
public class User {
private int id; //id
private String name; //姓名
private String pwd; //密碼
//構造,有參,無參
//set/get
//toString()
}
```
### 6.編寫 Mapper 介面
```java
import com.kuang.pojo.User;
import java.util.List;
public interface UserMapper {
List selectUser();
}
```
### 7.編寫 Mapper.xml 配置檔案
**注意 `namespace` 不要寫錯!**
```xml
```
### 8.編寫測試類
Junit 包測試
```java
public class MyTest {
@Test
public void selectUser() {
SqlSession session = MybatisUtils.getSession();
//方法一:
//List users = session.selectList("com.kuang.mapper.UserMapper.selectUser");
//方法二:
UserMapper mapper = session.getMapper(UserMapper.class);
List users = mapper.selectUser();
for (User user: users){
System.out.println(user);
}
session.close();
}
}
```
### 9.執行結果
## 出現的問題:
1、Maven 靜態資源過濾問題
```xml
src/main/java
**/*.properties
**/*.xml
false
src/main/resources
**/*.properties
**/*.xml
false