这是mybatis的架构图
我们从mybatis的查询来入手这个框架的理解
第一步:创建maven项目并添加依赖
第二步:配置mybatis-config.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="test">
<environment id="test">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/dbst?characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/StudentMapper.xml"></mapper>
</mappers>
</configuration>
第三步:编写mapper.xml文件,里面存放CURD的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="StudentMapper">
<select id="selectStudentList" resultType="com.etime.pojo.Student">
select * from student
</select>
<!-- 增加-->
<insert id="addStudent" parameterType="com.etime.pojo.Student">
insert into student(name,age,gender,major) values(#{name},#{age},#{gender},#{major})
</insert>
<!-- 修改-->
<update id="updateStudent" parameterType="com.etime.pojo.Student">
update student set name = #{name} where id = #{id}
</update>
<delete id="deleteStudent" parameterType="com.etime.pojo.Student">
delete from student where id = #{id}
</delete>
</mapper>
这个配置文件对应的就是架构图中的mybatis配置部分
第四步:在dao文件里创建一个SqlSessionFactory
private SqlSessionFactory createSessionFactory() throws IOException {
//定义sessionFactory
SqlSessionFactory sqlSessionFactory = null;
String resource = "mybatis-config.xml";
//读取配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
return sqlSessionFactory;
}
第五步:创建一个SqlSession会话并开启
SqlSession session = factory.openSession();
第六步:执行sql语句
List<Student> list = session.selectList("StudentMapper.selectStudentList");
第七步:mybatis根据映射文件执行语句
<mapper namespace="StudentMapper">
<select id="selectStudentList" resultType="com.etime.pojo.Student">
select * from student
</select>
</mapper>
第八步:如果需要传入参数则sql输入映射参数(如:插入操作)
main函数部分
//插入操作
Student student = new Student("ame",2,"male","gamer");
int add = studentDao.addStudent(student);
System.out.println(add);
mapper部分
<mapper namespace="StudentMapper">
<insert id="addStudent" parameterType="com.etime.pojo.Student">
insert into student(name,age,gender,major) values(#{name},#{age},#{gender},#{major})
</insert>
</mapper>
第九步:最后输出查询结果