定义接口,使得配置文件与接口相关联,
<mapper namespace="org.all.Mapper">
namespace是mpper.xml问价唯一的标识符
但调用接口中的方法的时候,就会自动的执行与之对应的SQL语句
接口中方法必须基于以下约定
方法名与mapper.xml文件中标签的id值相同
方法的输入参数与mapper.xml输入参数一样
方法的输出参数与mapper.xml文件中resulType类型一致
通过接口的方法名和id来实现一一对应
<?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.xml映射文件的唯一标识符 -->
<mapper namespace="org.all.Mapper">
<!-- 通过id来区分是哪个 resultType放回的对象-->
<!-- 动态传值#{id} -->
<select id="selectBlog" resultType="person" parameterType="int">
select * from person where id = #{id}
</select>
<!-- 输入参数和输出参数只能是一个 -->
<!-- #{id},#{name},#{age}必须是对象的属性 -->
<insert id="addPerson" parameterType="person">
insert into person values(#{id},#{name},#{age})
</insert>
<update id="updatePerson" parameterType="person">
update student set name=#{name},age=#{age} where id=#{id}
</update>
<delete id="deletePerson" parameterType="int">
delete person where id = #{id}
</delete>
<!-- 无论返回一个还是多个都是resultType -->
<select id="selecteAllPerson" resultType="person">
select * from person
</select>
</mapper>
person接口
package org.all;
//操作mybatis的接口
public interface Mapper {
//1.方法名与mapper.xml文件中标签的id值相同
//2.方法的输入参数与mapper.xml输入参数一样
//3方法的输出参数与mapper.xml文件中resulType类型一致
Person selectBlog(int x);
}
测试类
package org.all;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class Test {
public static void main(String[] args) throws IOException {
//加载Mybatis配置文件
Reader reader = Resources.getResourceAsReader("config.xml");
//sqlSessionFactory工厂
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sessionFactory.openSession();
Mapper mapper = session.getMapper(Mapper.class);
Person person = mapper.selectBlog(2);
System.out.println(person);
}
}