一、配置环境
![](https://i-blog.csdnimg.cn/blog_migrate/f935fe47ace3e8fc752e3f6f3de336cf.png)
使用MyBatis框架非常简单,只需在应用程序中引入MyBatis的核心包和lib目录中的依赖包即可。
二、创建项目
![](https://i-blog.csdnimg.cn/blog_migrate/8000bd500118f0a6b056e6d896ba228d.png)
需要用到的包有Mybatis、jdbc驱动包、Junit5(eclipse自带)
![](https://i-blog.csdnimg.cn/blog_migrate/5ab702ca27dc69fbcd2d3ba97eb6fe52.png)
注意:StudentMapper.xml是创建在Pojo包里,而mybatis-cofigure.xml是创建在src下
三、贴代码
log4j.properties
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.ssm=DEBUG
# 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
Student.java
package Pojo;
public class Student {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
StudentMapper.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表示命名空间 -->
<mapper namespace="Pojo.StudentMapper">
<!--根据学生编号获取学生信息 -->
<select id="findStudentById" parameterType="Integer"
resultType="Pojo.Student">
select * from t_student where id = #{id}
</select>
</mapper>
MybatisTest.java
package test;
import java.io.InputStream;
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;
impor