3、定义表Mapper的类
package com.xin;
public class StudentEntity {
private Integer studentId;
private String studentName;
private Integer studentAge;
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public Integer getStudentAge() {
return studentAge;
}
public void setStudentAge(Integer studentAge) {
this.studentAge = studentAge;
}
@Override
public String toString() {
return "StudentEntity{" +
"studentId=" + studentId +
", studentName='" + studentName + '\'' +
", studentAge=" + studentAge +
'}';
}
}
4、Mapper接口
package com.xin;
import java.util.List;
public interface StudentMapper {
List<StudentEntity> getByteStudent();
}
5、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">
<mapper namespace="com.xin.StudentMapper">
<resultMap id="studentEntityMapper" type="com.xin.StudentEntity">
<result column="id" property="studentId"></result>
<result column="name" property="studentName"></result>
<result column="age" property="studentAge"></result>
</resultMap>
<select id="getByteStudent" resultType="studentEntityMapper">
</select>
</mapper>
6、包装加载类
public class StudentServer {
private SqlSession sqlSession;
public StudentServer() throws IOException {
// 1.读取加载mybatis-config.xml
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2.获取到获取到
sqlSession = sqlSessionFactory.openSession();
}
public SqlSession getSqlSession() {
return sqlSession;
}
}
7、测试类
public class test {
public static void main(String[] args) throws IOException {
StudentServer studentServer = new StudentServer();
StudentMapper mapper = studentServer.getSqlSession().getMapper(StudentMapper.class);
System.out.println(mapper.getByteStudent());
studentServer.getSqlSession().close();
}
}
1.引入mybatis相关依赖 已经完成了
2.mybatis-config.xml(该配置文件名称是可以改) 存放就是我们数据库相关连接信息
3.定义mapper ----编写我们mybatis 相关 sql语句 每个表 对应一个mapper
4.定义java对象--需要注意下 类中的 成员属性与数据库表中字段 映射 默认 类中的 成员属性数据库表中字段名称对应的。
5.使用 mybatis api开始执行该 sql语句即可 得到结果