1.1安装mybatis和配置环境
1.Mybatis的下载地址:https://github.com/mybatis/mybatis-3/releases
2.Maven中Mybatis的依赖仓库下载地址:https://mvnrepository.com/artifact/org.mybatis/mybatis
Mybatis的依赖地址:
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.11</version>
</dependency>
1.2搭建数据库环境
在mysql数据库中创建mybatis数据库再导入users表存入数据
show databases;
create database mybatis;
use mybatis;
create table `users`(
`id` INT NOT NULL PRIMARY KEY,
`name` VARCHAR(20) DEFAULT NULL,
`pwd` VARCHAR(20) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
DESCRIBE `users`;
INSERT INTO `users`(`id`,`name`,`pwd`) VALUES
(1,'张三','123456'),
(2,'李四','134456'),
(3,'王五','151456'),
(4,'王二','156456')
1.3配置核心文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://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?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="111111"/>
</dataSource>
</environment>
</environments>
</configuration>
1.4编写Mybatis工具类
package com.ysp.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;
//工具类 SqlSessionFactory——> SqlSession
public class MybatisUtils {
//提升作用域
private static SqlSessionFactory sqlSessionFactory;
static {
//1.使用Mybatis获取SqlSessionFactory对象
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句
public static SqlSession getSqlSession(){
// SqlSession sqlSession = sqlSessionFactory.openSession();
// return sqlSession;
return sqlSessionFactory.openSession();
}
}
实现结果: