为什么要通过接口操作MyBatis
在以往的情况下,我们通过MyBatis操作数据库,每执行一条SQL语句就要实例化一个SqlSession,并且要调用相应的SQL映射文件信息。比如:
String statement = "com.dhj.entity.StudentMapper.delStudent";
操作有点麻烦,所以我们采用接口的形式,通过约定,进行更为简单的操作。
有一句话特别重要:约定优于配置,配置优于硬编码。
如何通过接口操作MyBatis
首先,文件结构如图所示:
其中,Student文件为一个普通的POJO对象
mapper文件下面是,SQL的配置文件和映射接口文件,我们约定,接口映射文件的类和xml配置文件名是一样的。
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">
<mapper namespace="com.krt.mapper.StudentMapper">
<!--namespace 填写映射文件的类路径-->
<!--id 名称 resultType 结果集类型 parameterType 输入类型-->
<select id="selectStudent" resultType="student" parameterType="int">
select * from Student where id = #{id}
</select>
<insert id="addStudent" parameterType="com.krt.entity.Student">
insert into Student value (#{id},#{name},#{age})
</insert>
<delete id="delStudent" parameterType="int" >
delete from Student where id = #{id}
</delete>
<update id="updateStudent" parameterType="com.krt.entity.Student">
update Student set name = #{name},age =#{age} where id = #{id}
</update>
<select id="selectAllStudent" resultType="student" >
select * from Student
</select>
</mapper>
StudentMapper接口类源码:(注意这是一个接口文件)
package com.krt.mapper;
import com.krt.entity.Student;
import java.util.List;
/*
* @Author 郭明德
* @Description
* @Date 2019/3/15 10:36
*
**/
//操作MyBatis接口
public interface StudentMapper {
/**
* 1,方法名和mapper.xml文件中的标签的id值相同
* 2,方法的输入参数和mapper.xml文件中的标签的parameterType类型一致
* 3,方法的返回值 和 mapper.xml文件中的标签的resultType类型一致
*/
//public abstract Student selectStudent(int id);
//查询一个学生
Student selectStudent(int id);
//查询全部
List<Student> selectAllStudent();
//增加
void addStudent(Student student);
//删除
int delStudent(int id);
//更新
void updateStudent(Student student);
}
这个接口文件,我们不进行实现,该接口是StudentMapper.xml的映射文件。相关约定见注解。
这样我们就可以通过调用该接口的相应的方法就可以调用相应的SQL语句。
我们只需要通过SqlSession对象,映射相应的SQL映射接口,然后调用相应的接口对象。
db.properties文件
该文件是一个用于存储连接数据库信息的文件。
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/test
username = root
password = root
这样就可以方便我们配置数据库信息。同时,在数据库发生问题,或者在项目交付使用之后要进行修改数据库都是非常方便的。
conf.xml中可以通过类似于EL表达式的方式调用。