官方推荐 原则优于配置 根据约定定位sql
1.新建接口 org.lanqiao.mapper.studentMapper
package org.lanqiao.mapper;
import org.lanqiao.entity.Student;
public interface studentMapper {
/**
* 本接口的全类名(org.lanqiao.mapper.studentMapper) =namespace的值
* 方法名和 Mapper.xml 文件id一致
* 参数类型 和 Mapper.xml 文件parameterType 一致
* 返回值 和 Mapper.xml 文件resultType 一致 **/
Student selectStudentById(int stuNo);
}
2.创建 映射文件studentAppointMapper.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="org.lanqiao.mapper.studentMapper">
<!-- parameterMap:输入参数 (基本类型,对象,map)resultType:返回参数(对象) -->
<select id="selectStudentById" resultType="org.lanqiao.entity.Student" parameterType="int">
select * from student where stuNo = #{stuno}
</select>
<insert id="addstudent" parameterType="org.lanqiao.entity.Student">
insert into student (stuNo ,stuName ,stuAge,graName) values(#{stuNo},#{stuName},#{stuAge},#{graName})
</insert>
<update id="updatestudent"></update>
<delete id="deleteStudentById" parameterType="int">
delete from student where stuNo = ${value}
</delete>
<!-- 返回值是对象 一个多个resultType都是一个对象 -->
<select id="selectStudentAll" resultType="org.lanqiao.entity.Student" >
select * from student
</select>
3.新增或者修改conf加载映射文件
<mapper resource="org/lanqiao/mapper/studentAppointMapper.xml" />
4.创建测试类
package org.lanqiao.entity;
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;
import org.lanqiao.mapper.studentMapper;
public class testAppoint {
public static void main(String[] args) throws Exception {
Reader reader= Resources.getResourceAsReader("conf.xml") ;
SqlSessionFactory sqlsessionfactory =new SqlSessionFactoryBuilder().build(reader,"development");
SqlSession sqlsession =sqlsessionfactory.openSession();
studentMapper studentmapper =sqlsession.getMapper(studentMapper.class);
Student Studentb =studentmapper.selectStudentById(1);
System.err.println(Studentb);
sqlsession.commit();
sqlsession.close();
}
}