MyBatis mapper代理方式

3. mapper代理方式(程序员只需mapper接口(相当于Dao的接口))

3.1   思路:1.程序员只需要写mapper接口(相当于Dao接口),mybatis可以自动生成mapper接口实现类的代理对象
2.程序员需要编写mapper.xml映射文件
3.开发规范:1.在mapper.xml中namespace等于mapper接口的地址


2.mapper接口中方法名和mapper.xml中的statement中的id一致
 3.mapper.java接口中的输入参数类型和mapper.xml中statement的parameterType的指定 类型一致
4.mapper.java接口中方法的返回类型和mapper.xml中resultType指定的类型一致
public Student findStudentById(int id) throws Exception;
总结:1.mapper.java public interface StudentMapper {
//根据ID查询学生信息
public Student findStudentById(int id) throws Exception;
2.mapper.xml 



3.测试方法
package top.haoyeyin.mapper;


import java.io.InputStream;

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.apache.log4j.BasicConfigurator;
import org.junit.Before;
import org.junit.Test;

public class StudentMapperTest {

private SqlSessionFactory sqlSessionFactory;
@Before
public void setup() throws Exception{
BasicConfigurator.configure();
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 创建会话工厂sessionFactory,传入SqlMapConfig.xml配置信息
sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);

}
@Test
public void testFindStudentById() {
SqlSession sqlSession=sqlSessionFactory.openSession();
//创建StudentMapper对象
StudentMapper studentMapper=sqlSession.getMapper(StudentMapper.class);

//调用studentMapper的方法
try {
studentMapper.findStudentById(4);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

你可能感兴趣的:(MyBatis)