Mybatis
简介
- Mybatis是一个半自动的ORM框架
- ORM(Object Relational Mapping)对象关系映射,将Java的一个对象与数据表中一行记录一一对应
ORM框架提供了实体类与数据表的映射关系,通过映射文件的配置,实现对象的持久化存储
特点
支持自定义SQL、存储过程
- 对原有的JDBC进行了封装,几乎消除了所有JDBC代码,让开发者只需关注SQL本身
- 支持XML和注解配置方式自定完成ORM操作,实现结果映射
部署
- 创建MAVEN项目
添加pom文件中的依赖 ```xml <?xml version=”1.0” encoding=”UTF-8”?> <project xmlns=”http://maven.apache.org/POM/4.0.0“
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0 org.example Mybatis 1.0-SNAPSHOT <maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<!--Mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<!-- junit单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
3. 添加Mybatis配置文件
```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">
<!--数据库连接配置-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://10.30.59.136/wy?serverTimezone=GMT&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--sql映射文件路径-->
<mappers>
<mapper resource="mappers/BookMapper"/>
</mappers>
</configuration>
Mybatis使用
- 创建数据表实体类 ```java package pojo;
public class Bookdatabase { public int getId() { return id; }
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Bookdatabase{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
private int id;
private String name;
private int age;
}
2. 创建接口类
```java
package dao;
import pojo.Bookdatabase;
import java.util.List;
public interface Bookdatamap {
public int insertBook(Bookdatabase book);
}
- 创建sql映射文件
<?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="dao.Bookdatamap">
<!--定义SQL语句,id为绑定的借口类中的方法名-->
<insert id="insertBook">
insert into test(id,name,age) values(#{id},#{name},#{age})
</insert>
</mapper>