mybatis annotation development one-to-many nested query

There are many students in a class, belonging to a one-to-many relationship. This article uses mybatis annotations and nested query methods to implement one-to-many queries. When querying classes based on classId, query and display the students in the class by the way

student实体类

package com.itheima.dao;

public class StudentDao {
    
    
    private Integer id;
    private String name;
    private Integer age;
    private Integer cid;

    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 Integer getAge() {
    
    
        return age;
    }

    public void setAge(Integer age) {
    
    
        this.age = age;
    }

    public Integer getCid() {
    
    
        return cid;
    }

    public void setCid(Integer cid) {
    
    
        this.cid = cid;
    }

    @Override
    public String toString() {
    
    
        return "StudentDao{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", cid=" + cid +
                '}';
    }
}

class实体类

package com.itheima.dao;

import java.util.List;

public class ClassDao {
    
    
    private Integer id;
    private String className;
    private List<StudentDao> studentsList;
    public Integer getId() {
    
    
        return id;
    }

    public void setId(Integer id) {
    
    
        this.id = id;
    }

    public String getClassName() {
    
    
        return className;
    }

    public void setClassName(String className) {
    
    
        this.className = className;
    }

    @Override
    public String toString() {
    
    
        return "ClassDao{" +
                "id=" + id +
                ", className='" + className + '\'' +
                ", studentsList=" + studentsList +
                '}';
    }
}

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">
<configuration>
    <!--设置连接数据库的环境-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url"
                          value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--引入映射文件-->
    <mappers>
        <mapper class="com.itheima.mapper.StudentMapper"/>
        <mapper class="com.itheima.mapper.ClassMapper"/>
    </mappers>

</configuration>

studentMapper.java

package com.itheima.mapper;

import com.itheima.dao.StudentDao;
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 java.util.List;

public interface StudentMapper {
    
    
    @Select("select * from student where cid = #{cid}")
    @Results({
    
    @Result(id = true, property = "id", column = "id"),
              @Result(property = "name",column = "name"),
              @Result(property = "age",column = "age"),
              @Result(property = "cid", column = "cid")})
    List<StudentDao> selectStudentByCid(Integer cid);
}

classMapper.java

package com.itheima.mapper;

import com.itheima.dao.ClassDao;
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 java.util.List;

public interface ClassMapper {
    
    
    @Select("select * from class where id = #{id}")
    @Results({
    
    @Result(id =true, property = "id",column = "id"),
              @Result(property = "className",column = "className"),
              @Result(property ="studentsList",column = "id",
                      many = @Many(select = "com.itheima.mapper.StudentMapper.selectStudentByCid"))})
    ClassDao selectClassById(Integer id);
}

testMybatis.java

import com.itheima.dao.ClassDao;
import com.itheima.dao.StudentDao;
import com.itheima.mapper.ClassMapper;
import com.itheima.mapper.StudentMapper;
import org.apache.ibatis.annotations.Mapper;
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.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class testMybatis {
    
    
   @Test
    public void test() throws IOException {
    
    
       InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
       SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
       SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
       SqlSession sqlSession = sqlSessionFactory.openSession(true);
       ClassMapper classMapper = sqlSession.getMapper(ClassMapper.class);
       ClassDao res = classMapper.selectClassById(2);
       System.out.println(res.toString());
   }
}

数据库sql文件

INSERT INTO `class` (`id`, `className`) VALUES (1, '软件19-1');
INSERT INTO `class` (`id`, `className`) VALUES (2, '软件19-2');
INSERT INTO `student` (`name`, `age`, `cid`, `id`) VALUES ('罗辑', 18, 2, 1);
INSERT INTO `student` (`name`, `age`, `cid`, `id`) VALUES ('张三', 18, 2, 2);
INSERT INTO `student` (`name`, `age`, `cid`, `id`) VALUES ('李四', 18, 2, 3);

As can be seen from the query results, the class information of Class 2 and the student information of Class 2
insert image description here
Notes:
1. In a one-to-many relationship, the primary key of the entity class of the "many" party that stores "one" is used as a foreign key , The entity class of the ''one'' side stores the list of the ''many'' side<entity class attribute of the many side> so that it can be displayed when querying. Define nested queries in the mapper interface on the "one" side.

Guess you like

Origin blog.csdn.net/qq_45486709/article/details/123797487