I. Resumen:
En el desarrollo real, la operación de la base de datos a menudo implica varias tablas, lo que implica la asociación entre objetos en la orientación a objetos. Para operaciones entre varias tablas, el marco MyBatis proporciona mapeo de asociación, a través del cual se puede manejar bien la asociación entre objetos.
2. Relación:
Veamos dos tablas, Profesor (tabla de profesores) y Enseñanza (tabla de cursos de enseñanza), y luego el número de trabajo del profesor (Tno) y el número de curso (cno) en esta tabla tienen una relación de uno a uno.
3. Relación uno a uno:
Para la relación analizada anteriormente, podemos ver el número de curso impartido por el profesor al consultar el número de trabajo del profesor, y también necesitamos agregar el atributo de enseñanza a la clase persistente Profesor. (Esto se considera desde el punto de vista del profesor)
Luego miramos su archivo de configuración Mapper.xml, primero vemos su interfaz correspondiente:
A continuación escribimos su archivo Mapper.xml
Luego puede escribir métodos de prueba de acuerdo con la interfaz.
Código uno:
1.Mapeador de profesores.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.example.mapper.TeacherMapper">
<select id="findTeacherByTno" parameterType="string" resultMap="classNameByID">
select * from teacher where Tno=#{Tno}
</select>
<resultMap id="classNameByID" type="Teacher">
<id property="Tno" column="Tno"></id>
<result property="Tname" column="Tname"></result>
<result property="Tsex" column="Tsex"></result>
<result property="Tbirthday" column="Tbirthday"></result>
<result property="deptno" column="deptno"></result>
<association property="teaching" column="tno" javaType="Teaching"
select="org.example.mapper.TeachingMapper.findCnameByTno"/>
</resultMap>
</mapper>
2.TeachingMapper.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.example.mapper.TeachingMapper">
<select id="findCnameByTno" parameterType="string" resultType="Teaching">
select * from teaching where tno=#{tno}
</select>
</mapper>
Método dos:
Código dos:
<?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.example.mapper.TeacherMapper">
<select id="findTeacherByTno" parameterType="string" resultMap="classNameByID">
SELECT * FROM teacher a RIGHT JOIN teaching b on a.Tno=b.tno where a.Tno=#{Tno}
</select>
<!-- <resultMap id="classNameByID" type="Teacher">-->
<!-- <id property="Tno" column="Tno"></id>-->
<!-- <result property="Tname" column="Tname"></result>-->
<!-- <result property="Tsex" column="Tsex"></result>-->
<!-- <result property="Tbirthday" column="Tbirthday"></result>-->
<!-- <result property="deptno" column="deptno"></result>-->
<!-- <association property="teaching" column="tno" javaType="Teaching"-->
<!-- select="org.example.mapper.TeachingMapper.findCnameByTno"/>-->
<!-- </resultMap>-->
<resultMap id="classNameByID" type="Teacher">
<id property="Tno" column="Tno"></id>
<result property="Tname" column="Tname"></result>
<result property="Tsex" column="Tsex"></result>
<result property="Tbirthday" column="Tbirthday"></result>
<result property="deptno" column="deptno"></result>
<association property="teaching" javaType="Teaching">
<id property="cno" column="cno"></id>
<result property="tno" column="tno"></result>
<result property="cterm" column="cterm"></result>
</association>
</resultMap>
</mapper>
3. Relación de uno a muchos:
Utilice la asociación para asignar a un atributo de ""tipo complejo" de JavaBean, como la clase JavaBean, es decir, un atributo de tipo de datos complejo (JavaBean) está anidado dentro de JavaBean, que pertenece a la asociación de tipo complejo. Sin embargo, debe ser señaló que los elementos de asociación solo manejan asociaciones uno a uno.
Por ejemplo, un departamento puede corresponder a varios maestros, luego necesitamos consultar un número de departamento y luego devolver el nombre del maestro que pertenece a este número de departamento. En este momento, usaremos una relación de uno a muchos, y luego usaremos la colección para Logrado.
Agregue una propiedad List<Teacher> que almacene la colección Teacher en la clase de entidad persistente Department
Agregar método a la interfaz de TeacherMapper
List<Teacher> findTeacherBydeptno(String deptno);
ProfesorMapper.xml
<select id="findTeacherBydeptno" parameterType="string" resultType="Teacher">
SELECT * FROM teacher WHERE deptno=#{deptno}
</select>
prueba:
Código:
<?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.example.mapper.DepartmentMapper">
<select id="findTeachersBydeptno" parameterType="string" resultMap="findteachsResult" >
SELECT * FROM department WHERE deptno=#{deptno}
</select>
<resultMap id="findteachsResult" type="Department">
<id property="deptno" column="deptno"></id>
<result property="deptname" column="deptname"></result>
<result property="deptheader" column="deptheader"></result>
<result property="office" column="office"></result>
<collection property="teachers" column="deptno" ofType="Teacher"
select="org.example.mapper.TeacherMapper.findTeacherBydeptno"/>
</resultMap>
</mapper>
Método dos:
4. Muchos a muchos:
En el desarrollo real, las relaciones de muchos a muchos también son muy comunes. En las escuelas, un estudiante elige varios cursos y muchos estudiantes eligen un curso. Esta es una relación de muchos a muchos. A continuación, entendemos cómo implementar una relación de muchos a muchos.
Luego primero cree dos clases persistentes Sc y Student
y sus correspondientes interfaces:
package org.example.mapper;
import org.apache.ibatis.annotations.Param;
import org.example.po.Student;
import java.util.List;
public interface StudentMapper {
List<Student> getStudent(@Param("cno")String cno);
}
package org.example.service;
import org.apache.ibatis.annotations.Param;
import org.example.po.Sc;
import java.util.List;
public interface ScService {
List<Sc> getSc(String cno);
}
Archivo de configuración del asignador:
StudentMapper.xml:
SCMapper.xml:
Código:
ScMapper.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.example.mapper.ScMapper">
<resultMap id="Sclist1" type="Sc">
<id property="sno" column="sno"></id>
<result property="cno" column="cno"></result>
<result property="degree" column="degree"></result>
<collection property="students" ofType="Student" column="cno"
select="org.example.mapper.StudentMapper.getStudent"/>
</resultMap>
<select id="getSc" parameterType="string" resultMap="Sclist1">
select * from sc
<if test="cno!=null and cno!=''">where cno=#{cno}</if>
</select>
</mapper>
StudentMapper.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.example.mapper.StudentMapper">
<select id="getStudent" resultType="Student" parameterType="string">
SELECT * from student WHERE sno IN (SELECT sno FROM sc WHERE cno=#{cno})
</select>
</mapper>
parte del servicio:
package org.example.service;
import org.apache.ibatis.annotations.Param;
import org.example.po.Sc;
import java.util.List;
public interface ScService {
List<Sc> getSc(String cno);
}
package org.example.service;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.example.mapper.ScMapper;
import org.example.po.Sc;
import java.util.List;
public class ScServiceImpl implements ScService{
private SqlSessionFactory sqlSessionFactory;
public ScServiceImpl(SqlSessionFactory sqlSessionFactory){
this.sqlSessionFactory=sqlSessionFactory;
}
@Override
public List<Sc> getSc(String cno) {
SqlSession sqlSession=sqlSessionFactory.openSession();
ScMapper scMapper=sqlSession.getMapper(ScMapper.class);
List<Sc> scs=scMapper.getSc(cno);
sqlSession.close();
return scs;
}
}
método de prueba:
package org.example;
import static org.junit.Assert.assertTrue;
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.example.mapper.TeacherMapper;
import org.example.po.Department;
import org.example.po.Sc;
import org.example.po.Student;
import org.example.po.Teacher;
import org.example.service.DepartmentServiceImpl;
import org.example.service.ScServiceImpl;
import org.example.service.TeacherServiceImpl;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* Unit test for simple App.
*/
public class AppTest
{
private SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws IOException {
InputStream in= Resources.getResourceAsStream("MyBatis_config.xml");
this.sqlSessionFactory=new SqlSessionFactoryBuilder().build(in);
}
// @Test
// public void findTeacherByTno(){
// TeacherServiceImpl teacherService=new TeacherServiceImpl(sqlSessionFactory);
// Teacher teacher=teacherService.findTeacherByTno("601");
// System.out.println(teacher);
// }
// @Test
// public void findteacherDeptno(){
// DepartmentServiceImpl departmentService=new DepartmentServiceImpl(sqlSessionFactory);
// List<Department> department=departmentService.findTeachersBydeptno("d01");
//
// }
@Test
public void getstudent(){
ScServiceImpl scService=new ScServiceImpl(sqlSessionFactory);
List<Sc> scs=scService.getSc(null);
for (Sc sc:scs){
System.out.println("课程编号为"+sc.getCno()+"的课:");
for(Student student:sc.getStudents()){
System.out.println("学生姓名为:"+student.getSname()+"学生班级为:"+student.getClassno());
}
}
}
}