MyBatis en muchas

Muchos entienden:

  • Un maestro con más estudiantes
  • Si un maestro aquí, es un fenómeno muchas que tiene un grupo de estudiantes de un maestro de abajo (colección)!

Base de datos puede referirse a muchos-a .

Ejemplo:


El siguiente ejemplo se basa en el entorno SpringBoot. Hay dos maneras de llevar a cabo un número de consultas.

Al igual que el procesamiento de consulta anidada de acuerdo con la sub-consulta en SQL
anidado consulta SQL procesamiento como tablas de contingencia de acuerdo con los resultados


Para citar un solo tipo, el proceso de anidación, de acuerdo con el resultado de tablas de contingencia en las consultas SQL. Se comprenderá mejor.

1. Dependencia pom.xml

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>


2. application.properties

mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.cc.pojo
mybatis.config-location=classpath:mybatis-config.xml
 
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mis?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8


3. El registro de configuración (estándar de registro utilizado aquí mybatis .STDOUT_LOGGING.)

SqlMapConfig.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">
<configuration>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
</configuration>


4 Código importante

1) El estudiante bajo el paquete POJO categoría, clase Maestro.

com.cc.pojo empaquetar; 

package com.cc.pojo;

import lombok.Data;

public class Student {
    private int id;
    private String name;
    private int tid;
    //GET,SET,ToString,有参,无参构造
}
package com.cc.pojo;

import java.util.List;

public class Teacher {
    private int id;
    private String name;
    //一个老师多个学生
    private List<Student> students;
}

2) en el asignador de interfaz.

com.cc.mapper empaquetar;
 

package com.cc.mapper;

import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface StudentMapper {

}
package com.cc.mapper;

import com.cc.pojo.Teacher;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface TeacherMapper {
    //获取指定老师,及老师下的所有学生
    public Teacher getTeacher(int id);
}

3) una interfaz correspondiente a la escritura Mapper perfil mapper.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="com.cc.mapper.StudentMapper">

</mapper>
<?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="com.cc.mapper.TeacherMapper">
        <!--
        思路:
            1. 从学生表和老师表中查出学生id,学生姓名,老师姓名
            2. 对查询出来的操作做结果集映射
                1. 集合的话,使用collection!
                    JavaType和ofType都是用来指定对象类型的
                    JavaType是用来指定pojo中属性的类型
                    ofType指定的是映射到list集合属性中pojo的类型。
        -->
        <select id="getTeacher" resultMap="TeacherStudent">
        select s.id sid, s.name sname , t.name tname, t.id tid
        from student s,teacher t
        where s.tid = t.id and t.id=#{tid}
    </select>

        <resultMap id="TeacherStudent" type="Teacher">
            <result property="id" column="tid"/>
            <result  property="name" column="tname"/>
            <collection property="students" ofType="Student">
                <result property="id" column="sid" />
                <result property="name" column="sname" />
                <result property="tid" column="tid" />
            </collection>
        </resultMap>
</mapper>

4) Prueba

package com.cc;

import com.cc.mapper.TeacherMapper;
import com.cc.pojo.Teacher;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TeacherTest {

    @Autowired
    private TeacherMapper teacherMapper;

    @Test
    public void testTeacher() {
        Teacher teacher = teacherMapper.getTeacher(2);
        System.out.println(teacher);
    }
}

5) los resultados operativos

Teacher{id=2, name='大老师', students=[Student(id=1, name=小明, tid=2), Student(id=2, name=小红, tid=2), Student(id=3, name=小张, tid=2), Student(id=4, name=小李, tid=2), Student(id=5, name=小王, tid=2)]}

 

Nota: resultMap asigna atributos no pueden ser menos tiempo, o de lo contrario perderán.

 

Para muchos-a-muchos y resumen:

  1. -asociación asociados
  2. -Colección colección
  3. Por lo que la asociación es muchos-a-uno y, mientras que la colección es de uno a muchos
  4. JavaType OfType y se utilizan para especificar el tipo de objeto

    • javaType atributo se utiliza para especificar el tipo de POJO
    • OfType lista especificada se asigna a un conjunto de tipos de atributos de POJO.

 


 

Publicados 272 artículos originales · ganado elogios 19 · Vistas a 20000 +

Supongo que te gusta

Origin blog.csdn.net/hello_cmy/article/details/104731135
Recomendado
Clasificación