代码:
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- XML 配置文件包含对 MyBatis 系统的核心设置 -->
<configuration>
<properties resource="db.properties"/>
<!-- 指定 MyBatis 所用日志的具体实现 -->
<settings>
<setting name="logImpl" value="LOG4J"/>
<!-- 要使延迟加载生效必须配置下面两个属性 -->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<environments default="mysql">
<!-- 环境配置,即连接的数据库。 -->
<environment id="mysql">
<!-- 指定事务管理类型,type="JDBC"指直接简单使用了JDBC的提交和回滚设置 -->
<transactionManager type="JDBC"/>
<!-- dataSource指数据源配置,POOLED是JDBC连接对象的数据源连接池的实现。 -->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- mappers告诉了MyBatis去哪里找持久化类的映射文件 -->
<mappers>
<mapper class="com.mapper.ClazzMapper"/>
<mapper class="com.mapper.StudentMapper"/>
</mappers>
</configuration>
Clazz.java
package com.bean;
import java.io.Serializable;
import java.util.List;
public class Clazz implements Serializable {
private Integer id; // 班级id,主键
private String code; // 班级编号
private String name; // 班级名称
// 班级和学生是一对多的关系,即一个班级可以有多个学生
private List<Student> students;
public Clazz() {
super();
// TODO Auto-generated constructor stub
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "Clazz [id=" + id + ", code=" + code + ", name=" + name + "]";
}
}
Student.java
package com.bean;
import java.io.Serializable;
public class Student implements Serializable {
private Integer id; // 学生id,主键
private String name; // 姓名
private String sex; // 性别
private Integer age; // 年龄
// 学生和班级是多对一的关系,即一个学生只属于一个班级
private Clazz clazz;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Clazz getClazz() {
return clazz;
}
public void setClazz(Clazz clazz) {
this.clazz = clazz;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "Student [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + "]";
}
}
FKSqlSessionFactory.java
package com.factory;
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;
public class FKSqlSessionFactory {
private static SqlSessionFactory sqlSessionFactory = null;
// 初始化创建SqlSessionFactory对象
static{
try {
// 读取mybatis-config.xml文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取SqlSession对象的静态方法
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
// 获取SqlSessionFactory的静态方法
public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
}
ClazzMapper.xml
package com.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;
import com.bean.Clazz;
import com.bean.Student;
public interface ClazzMapper {
@Select("SELECT * FROM TB_CLAZZ WHERE ID = #{id}")
@Results({
@Result(id=true,column="id",property="id"),
@Result(column="code",property="code"),
@Result(column="name",property="name"),
@Result(column="id",property="students",
many=@Many(
select="com.mapper.StudentMapper.selectByClazzId",
fetchType=FetchType.LAZY))
})
Clazz selectById(Integer id);
}
StudentMapper.xml
package com.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import com.bean.Student;
public interface StudentMapper {
// 根据班级id查询班级所有学生
@Select("select * from tb_student where clazz_id = #{id}")
@Results({
@Result(id=true,column="id",property="id"),
@Result(column="name",property="name"),
@Result(column="sex",property="sex"),
@Result(column="age",property="age")
})
List<Student> selectByClazzId(Integer clazz_id);
}
OneToManyTest.java
package com.test;
import org.apache.ibatis.session.SqlSession;
import com.bean.Clazz;
import com.factory.FKSqlSessionFactory;
import com.mapper.ClazzMapper;
public class OneToManyTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
SqlSession session = FKSqlSessionFactory.getSqlSession();
ClazzMapper cm =session.getMapper(ClazzMapper.class);
Clazz clazz = cm.selectById(1);
// 查看查询到的Clazz对象
System.out.println(clazz.getId()+" "+clazz.getCode()+" "+clazz.getName());
// 查看关联的学生集合,因为配置使用的是LAZY懒加载,所以当使用时才执行SQL语句
clazz.getStudents().forEach(student->System.out.println(student));
session.commit();
session.close();
}
}
截图: