您的位置:首页 > 移动开发

深入浅出Mybatis系列(八)---mapper映射文件配置之select、resultMap

2016-05-12 16:56 1061 查看
原文地址:http://www.cnblogs.com/dongying/p/4073259.html

上篇《深入浅出Mybatis系列(七)---mapper映射文件配置之insert、update、delete》 介绍了insert、update、delete的用法,本篇将介绍select、resultMap的用法。select无疑是我们最常用,也是最复杂 的,mybatis通过resultMap能帮助我们很好地进行高级映射。下面就开始看看select 以及 resultMap的用法:

先看select的配置吧:

package com.dy.dao;

import java.io.IOException;
import java.util.List;

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.junit.Test;

import com.dy.entity.Course;
import com.dy.entity.Student;

public class StudentDaoTest {

@Test
public void findCourseById() {
SqlSessionFactory sqlSessionFactory = getSessionFactory();
SqlSession sqlSession = sqlSessionFactory.openSession();
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
Student student = studentDao.findStudentById("20140101");
List<Course> courseList = student.getCourseList();
for (Course course: courseList) {
System.out.println(course.getId() + "   " + course.getName());
}
}

//Mybatis 通过SqlSessionFactory获取SqlSession, 然后才能通过SqlSession与数据库进行交互
private static SqlSessionFactory getSessionFactory() {
SqlSessionFactory sessionFactory = null;
String resource = "mybatis-conf.xml";
try {
sessionFactory = new SqlSessionFactoryBuilder().build(Resources
.getResourceAsReader(resource));
} catch (IOException e) {
e.printStackTrace();
}
return sessionFactory;
}
}


相信通过以上demo, 大家也能够使用mybatis的select 和 resultMap的用法了。上面demo只演示了一对多的映射,其实多对一、多对多也与它类似,所以我就没演示了,有兴趣的可以自己动手再做做。

好啦,本次就写到这儿了。(PS,生病一周了,所以到现在才更新博客)。

另附上demo, 需要的童鞋可以前往下载:

demo 下载地址:http://pan.baidu.com/s/1qWjsDzA

原文地址:http://www.cnblogs.com/dongying/p/4073259.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: