Mybatisアノテーションに基づく学生管理プログラム

Mybatisアノテーションに基づく学生管理プログラム

==この記事はダークホースプログラマーのケーススタディです==

必要とする

1.IDが2の学生情報を照会します。

2.idが4の学生の名前をLiLeiに変更し、年齢を21に変更します。

3.2番目のクラスのすべての生徒の情報に対する1対多のクエリ。

生徒用テーブルs_studentとクラス用テーブルを作成するc_class

学生(id) 学生の名前 学生の年齢(年齢) クラス(cid)
1 張三丰 18 1
2 Li Si 18 2
3 王呉 19 2
4 趙劉 20 1

クラスID) クラス名
1 1つのクラス
2 クラス2

テーブルステートメントの作成

use mybatis;
create table s_student
(
    id   int primary key auto_increment,
    name varchar(1314) not null,
    age  int           not null,
    cid  int           not null
);
insert into s_student( name, age, cid)
VALUES ('张三',18,1),('李四',18,2),('王五',19,2),('赵六',20,1);

create table c_class(
    id int primary key auto_increment,
    classname varchar(520) not null
);
insert into c_class(classname)values ('一班'),('二班');

Pojo親切

  • aClass(のキーワードClassjava非推奨)
package com.zjw.pojo;

import java.util.List;

public class aClass {
    
    
    private Integer id;
    private String classname;
    private List<Student> studentList;


    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;
    }

    public List<Student> getStudentList() {
    
    
        return studentList;
    }

    public void setStudentList(List<Student> studentList) {
    
    
        this.studentList = studentList;
    }

    @Override
    public String toString() {
    
    
        return "Class{" +
                "id=" + id +
                ", classname='" + classname + '\'' +
                ", studentList=" + studentList +
                '}';
    }
}
  • Student親切
package com.zjw.pojo;


public class Student {
    
    
    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 "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", cid=" + cid +
                '}';
    }
}

インターフェース

  • ClassMapper
package com.zjw.mapper;

import com.zjw.pojo.aClass;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

public interface ClassMapper {
    
    
    //一对多查询出二班所有学生的信息
    @Select("select * from c_class where id = #{id}")
    @Results({
    
    @Result(id = true, property = "id", column = "id"),
            @Result(property = "classname", column = "classname"),
            @Result(column = "id", property = "studentList",
                    many = @Many(select = "com.zjw.mapper.StudentMapper.selectStudentByCid"))})
    aClass selectStudentByClass(int id);

}
  • StudentMapper
package com.zjw.mapper;

import com.zjw.pojo.Student;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface StudentMapper {
    
    
    //查询id=2的学生信息
    @Select("select * from s_student where id = #{id}")
    Student selectStudentById(int id);

    //将id=4的学生姓名修改为李雷,年龄修改为21
    @Update("update s_student set name = #{name},age = #{age} where id = #{id}")
    int updateStudent(Student student);

    //一对多查询出二班所有学生的信息
    //此处的cid相当于外键
    @Select("select * from s_student where cid = #{id}")
    @Results({
    
    @Result(id = true, column = "id", property = "id"),
            @Result(column = "name", property = "name"),
            @Result(column = "age", property = "age")})
    List<Student> selectStudentByCid(int cid);

}

utilsツール

  • MybatisUtils
package com.zjw.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.Reader;

public class MybatisUtils {
    
    
    private static SqlSessionFactory sqlSessionFactory;

    static {
    
    
        try {
    
    
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

    public static SqlSession getSessioin() {
    
    
        return sqlSessionFactory.openSession();
    }

}

構成ファイル

  • pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>Demo04</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>16</maven.compiler.source>
        <maven.compiler.target>16</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>

    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>

            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>
  • 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>


    <properties resource="db.properties"/>

    <typeAliases>
        <package name="com.zjw.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">  <!--数据库连接池-->
                <property name="driver" value="${mysql.driver}"/>
                <property name="url" value="${mysql.url}"/>
                <!--serverTimezone=GMT是服务器时区-->
                <property name="username" value="${mysql.username}"/>
                <property name="password" value="${mysql.password}"/>
            </dataSource>
        </environment>
    </environments>


    <mappers>
        <mapper class="com.zjw.mapper.ClassMapper"/>
        <mapper class="com.zjw.mapper.StudentMapper"/>
    </mappers>

</configuration>

おすすめ

転載: blog.csdn.net/m0_57025749/article/details/123846791