基于MyBatis注解的
学生信息查询系统
一、步骤
1.引入相关依赖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>com.zjd</groupId>
<artifactId>Part3</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
2.导入数据库数据
1、新建数据库mybatis
CREATE DATABASE mybatis;
2、在mybatis数据库下创建表s_student
create table s_student(
id int primary key auto_increment,
name varchar(20) not null ,
age int not null ,
cid varchar(10)
);
3、在s_student表中插入数据
insert into s_student(name, age, cid) VALUES
('张三',18,1),
('李四',18,2),
('王五',19,2),
('赵六',20,1);
4、在mybatis数据库下创建表c_class
create table c_class(
id int primary key auto_increment,
classname varchar(20) not null
);
5、在c_class表中插入数据
insert into c_class(id, classname) VALUES
(1,'一班'),
(2,'二班')
3.创建连接数据库配置文件db.properties
# MySQL的版本在8.0之下的,mysql.driver=com.mysql.jdbc.Driver
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
mysql.username=root
mysql.password=root
4.创建myBatis的核心配置文件mybatis-config.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="db.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="com.zjd.mapper.StudentMapper"/>
<mapper class="com.zjd.mapper.ClassMapper"/>
</mappers>
</configuration>
5.创建student的实体类Student.java
package com.zjd.pojo;
import java.util.List;
public class Student {
private Integer id;
private String name;
private Integer age;
private Integer cid;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", cid=" + 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;
}
}
6.创建Student的接口映射文件StudentMapper.java
package com.zjd.mapper;
import com.zjd.pojo.Student;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface StudentMapper {
@Select("select * from s_student where id=#{id}")
Student findStudentById(int id);
@Update("update s_student set name=#{name},age=#{age} where id=#{id}")
int updateStudentById(Student student);
@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"),@Result(column = "cid",property = "cid")})
List<Student> selectStudentsByClassId(int cid);
}
7.创建class的实体类Class.java
package com.zjd.pojo;
import java.util.List;
public class Class {
private Integer id;
private String classname;
private List<Student> studentList;
@Override
public String toString() {
return "Class{" +
"id=" + id +
", classname='" + classname + '\'' +
", studentList=" + 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;
}
}
8.创建Class的接口映射文件ClassMapper.java
package com.zjd.mapper;
import com.zjd.pojo.Class;
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,column = "id",property = "id"),@Result(column = "id",property = "studentList",many = @Many(select = "com.zjd.mapper.StudentMapper.selectStudentsByClassId")),@Result(column = "classname",property = "classname")})
Class selectClassById(int id);
}
9.将映射文件加载到mybatis-config.xml中
<!-- 上图我已加载过 -->
<mappers>
<mapper class="com.zjd.mapper.StudentMapper"/>
<mapper class="com.zjd.mapper.ClassMapper"/>
</mappers>
8.创建MyBatis的工具类MyBatisUtils.java
package com.zjd.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 {
public static SqlSessionFactory sqlSessionFactory=null;
static {
try{
Reader reader= Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory= new SqlSessionFactoryBuilder().build(reader);
}catch (IOException e){
e.printStackTrace();
}
}
public static SqlSession getSession(){
return sqlSessionFactory.openSession();
}
}
9.创建测试类Test.java测试运行
import com.zjd.mapper.ClassMapper;
import com.zjd.mapper.StudentMapper;
import com.zjd.pojo.Class;
import com.zjd.pojo.Student;
import com.zjd.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import javax.sound.midi.Soundbank;
public class Test {
@org.junit.Test
public void findStudentById(){
SqlSession session= MyBatisUtils.getSession();
StudentMapper mapper=session.getMapper(StudentMapper.class);
Student student=mapper.findStudentById(2);
System.out.println(student);
session.close();
}
@org.junit.Test
public void updateStudentById(){
SqlSession session= MyBatisUtils.getSession();
StudentMapper mapper=session.getMapper(StudentMapper.class);
Student student=new Student();
student.setName("李雷");
student.setId(4);
student.setAge(21);
int result=mapper.updateStudentById(student);
if (result>0){
System.out.println("更新成功!");
}else {
System.out.println("更新失败!");
}
session.commit();
session.close();
}
@org.junit.Test
public void findStudentByClassId(){
SqlSession session=MyBatisUtils.getSession();
ClassMapper mapper=session.getMapper(ClassMapper.class);
Class classes=mapper.selectClassById(2);
System.out.println(classes);
session.close();
}
}