Programme de gestion des étudiants basé sur l'annotation Mybatis
== Cet article est une étude de cas de programmeurs dark horse ==
Exiger
1. Interrogez les informations sur l'étudiant dont l'identifiant est 2 ;
2. Changez le nom de l'étudiant dont l'identifiant est 4 en Li Lei et l'âge en 21 ;
3. Requête un-à-plusieurs pour les informations de tous les élèves de la deuxième classe ;
Créer une table d'élèves et une table s_student
de classec_class
Carte d'étudiant) | nom d'étudiant | Âge de l'étudiant (âge) | Classe (cid) |
---|---|---|---|
1 | Zhang San | 18 | 1 |
2 | Li Si | 18 | 2 |
3 | Wang Wu | 19 | 2 |
4 | Zhao Liu | 20 | 1 |
identifiant de classe) | nom du cours |
---|---|
1 | une classe |
2 | classe deux |
créer une instruction de table
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
type
aClass
( mot-cléClass
pourjava
, non recommandé)
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
type
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 +
'}';
}
}
interface
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
Outils
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();
}
}
fichier de configuration
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>