MyBatis友人帐之一对多和多对一处理

一、概念

多对一的理解:

  • 多个学生对应一个老师

  • 如果对于学生这边,就是一个多对一的现象,即从学生这边关联一个老师!

1.1数据库设计

CREATE TABLE `teacher` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师');

CREATE TABLE `student` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8


INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');

1.2idea配置




    

    
    
        
    
    
        
    
    
        
            
            
                
                
                
                
            
        
    
    
        
        
    

1.3其他配置

数据库配置文件

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
username=root
password=b123456

日志文件

#????DEBUG????????console?file???????console?file?????????
log4j.rootLogger=DEBUG,console,file

#??????????
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n

#?????????
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/kuang.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n

#??????
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

1.4编写实体类

package com.yanyu.pojo;

import lombok.Data;

@Data
public class Student {
    private int id;
    private String name;
    //多个学生可以是同一个老师,即多对一
    private Teacher teacher;
}
package com.yanyu.pojo;

import lombok.Data;

@Data //GET,SET,ToString,有参,无参构造
public class Teacher {
    private int id;
    private String name;
}

1.5编写接口

package com.yanyu.dao;

public interface StudentMapper {
}
package com.yanyu.dao;

import com.yanyu.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

public interface TeacherMapper {
    @Select("select * from teacher where id = #{tid}")
    Teacher getTeacher (@Param("tid") int id);
}

1.6编写实体类配置









1.7控制

package com.yanyu.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 {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取SqlSession连接
//    public static SqlSession getSession(){
//        return sqlSessionFactory.openSession();
//    }
    //获取SqlSession连接
    public static SqlSession getSession(){
        return getSession(true); //事务自动提交
    }

    public static SqlSession getSession(boolean flag){
        return sqlSessionFactory.openSession(flag);
    }

}

二、多对一的需求

2.1按查询嵌套处理

给StudentMapper接口增加方法

//获取所有学生及对应老师的信息
public List getStudents();

编写对应的Mapper文件





    
    
    
        
        
    
    
    

:定义了一个StudentTeacher结果映射,它将数据库查询的结果映射到Student类上,并且Student类中有一个复杂类型的属性teacher,它需要传入两个参数id和name,它们对应数据库中的tid列,并且teacher属性值是通过调用getTeacher这个SQL语句来获取的。

测试

 @Test
    public void testGetStudents(){
        SqlSession session = MybatisUtils.getSession();
        StudentMapper mapper = session.getMapper(StudentMapper.class);

        List students = mapper.getStudents();

        for (Student student : students){
            System.out.println(
                    "学生名:"+ student.getName()
                            +"\t老师:"+student.getTeacher().getName());
        }
    }

2.2按结果嵌套处理

接口方法编写

public List getStudents2();

编写对应的mapper文件



   
   

测试

@Test
public void testGetTeacher2(){
   SqlSession session = MybatisUtils.getSession();
   TeacherMapper mapper = session.getMapper(TeacherMapper.class);
   Teacher teacher = mapper.getTeacher2(1);
   System.out.println(teacher.getName());
   System.out.println(teacher.getStudents());
}

2.3小结

按照查询进行嵌套处理就像SQL中的子查询

按照结果进行嵌套处理就像SQL中的联表查询

三、 一对多处理

一对多的理解:

  • 一个老师拥有多个学生

  • 如果对于老师这边,就是一个一对多的现象,即从一个老师下面拥有一群学生(集合)!

 3.1环境配置

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

3.2按结果嵌套处理

TeacherMapper接口编写方法

//获取指定老师,及老师下的所有学生
public Teacher getTeacher(int id);

编写接口对应的Mapper配置文件




    
    

    
        
        
            
            
            
        
    

测试

@Test
public void testGetTeacher(){
   SqlSession session = MybatisUtils.getSession();
   TeacherMapper mapper = session.getMapper(TeacherMapper.class);
   Teacher teacher = mapper.getTeacher(1);
   System.out.println(teacher.getName());
   System.out.println(teacher.getStudents());
}

3.3按查询嵌套处理

TeacherMapper接口编写方法

public Teacher getTeacher2(int id);

编写接口对应的Mapper配置文件


    
        
        
    
    

测试

@Test
public void testGetTeacher2(){
   SqlSession session = MybatisUtils.getSession();
   TeacherMapper mapper = session.getMapper(TeacherMapper.class);
   Teacher teacher = mapper.getTeacher2(1);
   System.out.println(teacher.getName());
   System.out.println(teacher.getStudents());
}

3.4小结

1、关联-association

2、集合-collection

3、所以association是用于一对一和多对一,而collection是用于一对多的关系

4、JavaType和ofType都是用来指定对象类型的

  • JavaType是用来指定pojo中属性的类型

  • ofType指定的是映射到list集合属性中pojo的类型。

你可能感兴趣的:(mybatis,java,数据库)