一、MyBatis介绍
1. 为什么要使用MyBatis?
- (1)Mybatis是一个半ORM(对象关系映射)框架,它内部封装了JDBC,开发时只需要关注SQL语句
本身,不需要花费精力去处理加载驱动、创建连接、创建statement等繁杂的过程。程序员直接编写原
生态sql,可以严格控制sql执行性能,灵活度高。 - (2)MyBatis 可以使用 XML 或注解来配置和映射原生信息,将 POJO映射成数据库中的记录,避免了
几乎所有的 JDBC 代码和手动设置参数以及获取结果集。 - (3)通过xml 文件或注解的方式将要执行的各种 statement 配置起来,并通过java对象和 statement
中sql的动态参数进行映射生成最终执行的sql语句,最后由mybatis框架执行sql并将结果映射为java对
象并返回。(从执行sql到返回result的过程)。
2. 什么是MyBatis
- mybatis是一款用于持久层的、轻量级的半自动化ORM框架,封装了所有jdbc操作以及设置查询参数和获取结果集的操作,支持自定义sql、存储过程和高级映射。
二、MyBatis入门
userdao
package com.by.mapper;
import com.by.pojo.User;
import org.apache.ibatis.annotations.Param;
public interface UserDao {
//利用单个元素查询
User getUserById(Integer id);
}
userdao.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">
<!--namespace:隔离sql,一般是接口名称的全类名-->
<mapper namespace="com.by.mapper.UserDao">
<select id="getUserById" parameterType="java.lang.Integer" resultType="com.by.pojo.User">
select * from user where id = #{id}
</select>
</mapper>
user
package com.by.pojo;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable {
private Integer id;
private String username;
private String password;
private Date birthday;
private String sex;
private String address;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
pom.xml
<properties>
<!--项目编译JDK版本-->
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<!--项目源码及编译输出的编码-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<build>
<!-- 如果不添加此节点src/main/java目录下的所有配置文件都会被漏掉。 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
log4j.prolperties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
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>
<!-- 和spring整合后 environments配置将废除-->
<environments default="dev">
<!-- dev环境 -->
<environment id="dev">
<!-- 配置事务的类型 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置连接数据库的信息:用的是数据源(连接池) -->
<dataSource type="POOLED">
<!-- 此处为MySql版本为8.0及以上写法 -->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSsL=false&serverTimezone=Asia/Shanghai"/>
<!-- 此处为MySql版本低于8.0写法 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?useSSsL=false&serverTimezone=Asia/Shanghai"/>
<property name="username" value="MySql用户名"/>
<property name="password" value="MySql密码"/>
</dataSource>
</environment>
</environments>
<!-- 告知 mybatis 映射配置的位置 -->
<mappers>
<mapper resource="com/by/mapper/UserDao.xml"/>
</mappers>
</configuration>
UserTest
package com.by.test;
import com.by.pojo.User;
import com.by.mapper.UserDao;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UserTest {
private InputStream inputStream;
private SqlSession sqlSession;
@Before
public void createSqlSession() throws IOException {
// 加载配置文件
String resource = "mybatis-config.xml";
inputStream = Resources.getResourceAsStream(resource);
// 创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获得数据库会话实例
sqlSession = sqlSessionFactory.openSession();
}
@Test
public void testgetUserById() throws IOException {
UserDao userDao = sqlSession.getMapper(UserDao.class);
User user=userDao.getUserById(43);
System.out.println(user);
}
@After
public void Close()throws IOException {
sqlSession.close();
inputStream.close();
}
}
三、MyBatis运行原理
mybatis-config.xml
mapper.xml mapper.xml mapper.xml
|
|
Resources
|
|---->inputStream
|
SqlSessionFactoryBuilder
|
|--->Configuration(conn, Map<namespace+id, MappedStatement(sql,resultType)>)
|
SqlSessionFactory
|
|--->Configuration(conn, Map<namespace+id, MappedStatement(sql,resultType)>)
|
SqlSession
|
|--->Map<namespace+id, MappedStatement(sql,resultType)>, conn
|
ProxyFactory
|
|--->mappedStatement,conn
|
Executor
| |
| |
| |
输入参数映射 输出结果映射
四、MyBatis传递参数
1、序号传递多个参数
WHERE id=#{arg0} AND username=#{arg1}
WHERE id=#{param1} AND username=#{param2}
2、注解传递多个参数—【推荐】
User getUser2(@Param(“id”) Integer id, @Param(“username”) String username);
select * from user where id=#{id} and username=#{username}
3、pojo传递多个参数—【推荐】
User getUser3(User user);
select * from user where id=#{id} and username=#{username}
4、map传递多个参数
User getUser3(Map user);
select * from user where id=#{id} and username=#{username}
五、MyBatis中$ 和#的区别
六、mybatis的主键回填