环境搭建
- 搭建数据库
CREATE DATABASE mybatis;
use mybatis;
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;
SELECT * FROM user;
INSERT INTO USER ( id, NAME, pwd )
VALUES
(1, "佩奇", '123'),
(2,"乔恩",'123' ),
(3,"张三",'123' );
- 新建项目maven项目
需要导入的依赖
<!-- 父项目-->
<!-- 导入依赖-->
<dependencies>
<!-- mysql驱动-->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 导入mybatis-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!-- junit -->
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
添加的配置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核心配置文件-->
<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?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="990801lxq"/>
</dataSource>
</environment>
</environments>
</configuration>
编写工具类
package cn.at99guoke.utils;
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 {
//获取SqlSessionFactory对象
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
//
}
// 获得 SqlSession 的实例
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}