1.导入依赖
pom.xml
<dependencies>
<!-- Mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- Mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<!-- 测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
2.在Resource下面创建Mybatis-config.xml
并把下面内容复制进去,然后配置数据库连接信息
<?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="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
3.创建Mapper接口
MyBatis中的mapper接口相当于以前的Dao但是区别在于,mapper仅仅是接口,我们不需要提供实现类。
实体类
package com.mybatis.Bean;
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
public User(Integer id, String username, String password, Integer age) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
}
public User() {
}
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
Mapper类
package com.mybatis.Mapper;
public interface UserMapper {
}
项目结构图
4.创建Mybatis映射文件
<!-- 引入映射文件-->
<mappers>
<mapper resource="Mappers/UserMapper.xml"/>
</mappers>
5.
MyBatis面向接口编程的两个一致:
1、映射文件的namespace要和mapper接口的全类名保持一致
2、映射文件中SQL语句的id要和mapper接口中的方法名一致
public interface UserMapper {
int insertUser();
}
<?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.mybatis.Mapper.UserMapper">
<insert id="insertUser">
insert into user values (null,"cc","123445",20);
</insert>
</mapper>