1.创建工程
2.引入相关的依赖 pom.xml
<dependencies><!--1.引入mybatis包--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.6</version></dependency><!--2.单元测试--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><!--3.mysql驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.18</version><scope>runtime</scope></dependency><!--4.log4j日志--><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency></dependencies>
3.准备数据库
这里使用的是数据库是mybatis
use mybatis;
create table users(uid int primary key auto_increment,uname varchar(20) not null,uage int not null
);
insert into users(uid,uname,uage) values(null,'张三',20),(null,'李四',18);
4.创建mybatis的核心配置文件所使用的db.properties文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
jdbc.username=root
jdbc.password=root
5.创建项目结构
5.1 创建com.example.pojo包存放实体类User
实体类User的内容如下
package com.example.pojo;/*** ClassName: User* Package: com.example.pojo* Description:** @Create 2023/3/16 7:52* @Version 1.0*/
public class User {private int uid;private String uname;private int uage;public int getUid() {return uid;}public void setUid(int uid) {this.uid = uid;}public String getUname() {return uname;}public void setUname(String uname) {this.uname = uname;}public int getUage() {return uage;}public void setUage(int uage) {this.uage = uage;}@Overridepublic String toString() {return "User{" +"uid=" + uid +", uname='" + uname + '\'' +", uage=" + uage +'}';}
}
5.2 创建com.example.mapper包存mapper接口
UserMapper接口如下
package com.example.mapper;/*** ClassName: UserMapper* Package: com.example.mapper* Description:** @Create 2023/3/16 7:55* @Version 1.0*/
public interface UserMapper {
}
6.创建Mybatis核心配置文件mybatis-config.xml
mybatis-config.xml内容如下
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!--引入properties文件--><properties resource="db.properties"></properties><!--将下划线映射为驼峰--><settings><setting name="mapUnderscoreToCamelCase" value="true"/></settings><!--设置类型别名--><typeAliases><!--以包为单位,将包下所有的类型设置设置默认的类型别名,即类名且不区分大小写--><package name="com.example.pojo"/></typeAliases><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></dataSource></environment></environments><!-- 引入映射文件 --><mappers><!--以包为单位引入映射文件要求:1. mapper接口所在的包要和映射文件所在的包一致2. mapper接口要和映射文件的名字一致--><package name="com.example.mapper"/></mappers></configuration>
7.创建Mybatis映射文件UserMapper.xml
7.1创建目录结构
7.2 UserMapper.xml内容如下
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper"><!-- namespace要和mapper接口的全类名保持一致 --><!-- sql语句要和接口的方法名保持一致 --></mapper>
8.创建log4j.xml的配置文件
内容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"><log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"><appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"><param name="Encoding" value="UTF-8"/><layout class="org.apache.log4j.PatternLayout"><param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n"/></layout></appender><logger name="java.sql"><level value="debug"/></logger><logger name="org.apache.ibatis"><level value="info"/></logger><root><level value="debug"/><appender-ref ref="STDOUT"/></root>
</log4j:configuration>
9.创建测试文件TestMybatis.java
9.第一个测试案例
根据User的id查找User
9.1 com.example.mapper.UserMapper.java接口文件中添加方法
public interface UserMapper {/*** 根据用户id查找用户*/public User findUserById(int id);
}
9.2 UserMapper.xml映射文件添加sql语句
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper"><!-- namespace要和mapper接口的全类名保持一致 --><!-- sql语句要和接口的方法名保持一致 --><select id="findUserById"parameterType="int"resultType="User">select * from users where uid = #{id}</select>
</mapper>
9.3 com.example.test.TestMybatis.java中添加测试方法
package com.example.test;import com.example.mapper.UserMapper;
import com.example.pojo.User;
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.Test;import java.io.IOException;
import java.io.InputStream;/*** ClassName: TestMyBatis* Package: com.example.test* Description:** @Create 2023/3/16 8:07* @Version 1.0*/
public class TestMyBatis {@Testpublic void testFindUserById() throws IOException {//1.获取核心配置类InputStream is = Resources.getResourceAsStream("mybatis-config.xml");//2.创建SqlSessionFacotrySqlSessionFactory sqlSessionFacotry = new SqlSessionFactoryBuilder().build(is);//3.获取SqLSession对象SqlSession session = sqlSessionFacotry.openSession();//4.执行sql语句UserMapper mapper = session.getMapper(UserMapper.class);User user = mapper.findUserById(1);System.out.println("user = " + user);//5。释放资源session.close();}
}