为什么使用Mybatis
传统JDBC的弊端
- 影响性能:数据库连接,使用时就创建,不用就释放。对数据库频繁开关,浪费资源,使性能下降。
- 不利于维护:sql语句、preparedStatement参数值、resultSet结果集 硬编码到java代码中,如果sql语句修改,需要重新编译java代码。
Mybatis优势
- 简化操作,提供连接池控制连接
- java文件分离,分离成业务接口+SQLMapper.xml
- 免去设置参数和结果集的操作
Mybatis介绍
基于ORM思想
Mybatis使用
配置连接
依赖包
- mybatis.jar
- mysql-connector-java.jar
- junit.jar
- hamcrest-core-1.3.jar
mybatis-config.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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<!-- JDBC:驱动,地址,用户名,密码 -->
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/exam?useUnicode=true&characterEncoding=utf8" />
<property name="username" value="root" />
<property name="password" value="123456" />
<!-- 默认情况下:池中有10个连接存在! -->
</dataSource>
</environment>
<!-- 还可以配置多个其它的环境:test product -->
<!-- <environment id="test">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment> -->
</environments>
</configuration>
创建SqlSession会话对象
package com.Week_6.day2_16.util;
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;
/**
* @ClassName Util
* @Description //Session会话
* @Author 16014
* @Date 2022/2/15 16:01
* @Version 1.0
**/
public class SessionUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
public static SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
创建Sql连接池
编写过程
编写实体类
public class StudentEntity {
private long id;
private String stu_name;
private String gender;
}
编写接口
//根据ID查询
public interface StudentMapper {
StudentEntity getStudentById(long id);
}
在mapper.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="com.Week_6.day2_16.mapper.StudentMapper">
<!--数据库映射-->
<!--type:映射的实体类;property:实体类对象名;column:数据库字段名;javaType:把对象的数据类型通过javaType转换成数据库字段对应的类型-->
<resultMap type="StudentEntity" id="stumap">
<id property="id" column="id" javaType="long"/>
<result property="stu_name" column="stu_name" javaType="string"/>
<result property="gender" column="gender" javaType="string"/>
</resultMap>
对应的数据类型