配置工具类
package com.li.utils;
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 java.io.IOException;
import java.io.InputStream;
public class MybatisUtils {
public static SqlSessionFactory sqlSessionFactory;
static {
//构建 SqlSessionFactory对象
try {
String resource = "MybatisConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
}
根据数据库创建pojo对象
student对象
package com.li.pojo;
import lombok.Data;
@Data
public class Student {
public int sid;
public String sname;
public Teacher teacher;
}
teacher对象
package com.li.pojo;
import lombok.Data;
@Data
public class Teacher {
public String tid;
public String tname;
}
创建mapper接口
StudentMapper
package com.li.mapper;
import com.li.pojo.Student;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface StudentMapper {
public List studentList(@Param("id") int id);
}
TeacherMapper
package com.li.mapper;
import com.li.pojo.Student;
import java.util.List;
public interface TeacherMapper {
List teachertList();
}
resources目录
StudentMapper.xml在resources文件下创建相同与mapper相同目录结构的目录
TeacherMapper.xmlselect * from Student where sid=#{id}
测试
创建相同目录结构的测试类
package com.li.mapper;
import com.li.pojo.Student;
import com.li.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class test {
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List students = mapper.studentList(123);
for (Student student : students) {
System.out.println(student);
}
sqlSession.close();
}
}
重点
主要是在StudentMapper.xml配置的ResultMap映射
ResultMap附目录结构select="teacherList"> property:表示pojo中对象的属性
column:表示数据库中要查询的字段名称,由column属性映射到property属性
javaType:指定返回值类型
select:表示要将column值传递到的地方id属性与select的值相同,也必须和TeacherMapper接口中的方法相同



