使用mybatis对学生管理系统的完整功能实现

一、什么是mybatis:

      MyBatis 是一个优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects) 映射成数据库中的记录。

以下是 MyBatis 的一些核心特性:

  1. SQL 编写的灵活性:MyBatis 允许开发者编写原生 SQL 语句,提供了极高的灵活性。

  2. 映射的灵活性:MyBatis 支持将 SQL 语句的结果集映射到 Java 对象中,也可以将 Java 对象映射到 SQL 语句的参数中。

  3. 配置的灵活性:MyBatis 可以通过 XML 或注解来配置映射,提供了灵活的配置方式。

  4. 支持存储过程:MyBatis 支持调用数据库的存储过程。

  5. 事务管理:MyBatis 提供了事务管理的支持,可以方便地进行事务控制。

  6. 缓存机制:MyBatis 提供了一级和二级缓存机制,可以提高查询效率。

  7. 插件支持:MyBatis 允许开发者通过插件来扩展其功能。

  8. 与 Spring 集成:MyBatis 可以与 Spring 框架无缝集成,利用 Spring 的依赖注入和事务管理功能。

二、mybatis的好处:

  1. 简单易用:MyBatis 的学习曲线相对较低,它提供了清晰的 API 和简单的配置,使得开发者可以快速上手。

  2. 灵活的 SQL 支持:MyBatis 允许开发者编写原生 SQL 语句,这意味着你可以充分利用数据库的特性,如复杂的连接、子查询等。

  3. 映射的灵活性:MyBatis 提供了丰富的结果映射选项,可以将 SQL 查询的结果映射到 Java 对象、Java 集合或简单类型。

  4. 支持存储过程:MyBatis 支持调用数据库的存储过程,这对于需要执行复杂数据库操作的应用程序非常有用。

  5. 缓存机制:MyBatis 提供了一级和二级缓存机制,可以显著提高应用程序的性能,特别是在读取密集型的应用中。

  6. 事务管理:MyBatis 支持声明式事务管理,可以轻松地与 Spring 集成,利用 Spring 的事务管理功能。

  7. 可扩展性:MyBatis 允许开发者通过插件机制扩展其功能,例如添加自定义的类型处理器或拦截器。

  8. 与 Spring 集成:MyBatis 可以与 Spring 框架无缝集成,利用 Spring 的依赖注入和事务管理功能,简化数据库操作的配置和使用。

  9. 减少样板代码:MyBatis 通过 SQL 映射和结果映射减少了 JDBC 代码中的样板代码,使得开发者可以更专注于业务逻辑。

  10. 支持多种数据库:MyBatis 支持多种数据库,如 MySQL、PostgreSQL、Oracle 等,这使得它在多种数据库环境中都能使用。

  11. 社区支持:MyBatis 有一个活跃的社区,提供了大量的文档、教程和论坛支持,这有助于解决开发过程中遇到的问题。

  12. 性能:MyBatis 的性能通常与手写 JDBC 相当,而且由于其缓存机制,有时甚至可以提供更好的性能。

 三、如何使用 MyBatis 进行数据库的 CRUD 操作

1.添加 MyBatis 依赖

首先,在你的项目中添加 MyBatis 的依赖。如果你使用的是 Maven,可以在 pom.xml 文件中添加如下依赖:

<dependency>
//测试的依赖,可以对代码进行代码块测试
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
//mysql的依赖
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.22</version>
    </dependency>
//日志的依赖
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>
        1.2.12
      </version>
    </dependency>
//mybatis的依赖
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.5</version>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>RELEASE</version>
      <scope>compile</scope>
    </dependency>

2.配置 MyBatis

创建config文档,创建 MyBatis 的配置文件 mybatis-config.xml,并配置数据库连接信息和 Mapper 资源,(以及添加日志的配置文件)

b13724bd582f48528a96e9f1e8fdac76.png

<?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="develop">
        <environment id="develop">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/xsgl?serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
//添加mapper文件的地址
        <mapper resource="mapper/StudentMapper.xml"/>
    </mappers>
</configuration>

3.创建 Mapper 接口

定义一个 Mapper 接口,里面包含你需要执行的 CRUD 操作的方法。

package Dao;

import Model.Student;
import Model.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface StudentDao {
    List<Student> findAll();
    int findAll1(String zh, String pw);
    int deleteData(int id);
    int updateData(Student student);
    int insertData(Student student)
   }

4.编写 Mapper XML 文件

创建一个 XML 文件来映射 SQL 语句到 Mapper 接口的方法

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC
        "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="Dao.StudentDao">
    <select id="findAll" resultType="Model.Student">
        select * from student
    </select>
    <select id="findAll1" resultType="Model.User">
        select * from user where sname=#{sname} and password=#{password}
    </select>
    <delete id="deleteData">
        delete from student where id=#{id}
    </delete>
    <update id="insertData">
        insert into student values(null,#{name},#{sex},#{age},#{major},#{time})
    </update>
    <update id="updateData">
        update student set name=#{name},sex=#{sex},age=#{age},major=#{major},time=#{time} where id=#{id};
    </update>
</mapper>

 

5.使用 SqlSessionFactory

在应用程序中创建 SqlSessionFactory 实例,并使用它来获取 Mapper 接口的代理对象。 

    private static InputStream in;
    private static SqlSessionFactory factory;
    private static SqlSession sqlSession;
    static StudentDao studentDao;
    /**
     * 配置文件封装
     * @throws IOException
     */
    public static void start() throws IOException {
        in = Resources.getResourceAsStream("config/mybatis_config.xml");
        factory = new SqlSessionFactoryBuilder().build(in);
        sqlSession = factory.openSession();
        studentDao = sqlSession.getMapper(StudentDao.class);
    }

 

6.执行 CRUD 操作

在你的业务逻辑中,使用 SqlSession 来执行 CRUD 操作。

在示例中是学生管理系统所以我放在数据访问层处理

package Dao;

import Model.Student;
import Model.User;
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.apache.log4j.PropertyConfigurator;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

public class DaoStuHandle {
    private static InputStream in;
    private static SqlSessionFactory factory;
    private static SqlSession sqlSession;
    static StudentDao studentDao;
    /**
     * 配置文件封装
     * @throws IOException
     */
    public static void start() throws IOException {
        in = Resources.getResourceAsStream("config/mybatis_config.xml");
       //获取一个工厂对象
        factory = new SqlSessionFactoryBuilder().build(in);
  //通过工厂获取一个对象
        sqlSession = factory.openSession();
        studentDao = sqlSession.getMapper(StudentDao.class);
    }
//日志文件的添加
    public static void info() throws IOException {
       Properties properties = new Properties();
        FileInputStream fileInputStream = new FileInputStream("src/main/resources/config/log4j.properties");
        properties.load(fileInputStream);
        PropertyConfigurator.configure(properties);
    }

    public void showStuDAO() throws Exception {
        DaoStuHandle.start();
        List<Student> all=studentDao.findAll();
        for (Student stu:all){
            System.out.println("stu = " + stu);
        }

    }


    public void addStuDAO(Student student3) throws Exception {
        DaoStuHandle.start();
        int i = studentDao.insertData(student3);
        if (i!=0){
            System.out.println("添加成功");
        }else {
            System.out.println("添加失败");
        }
        sqlSession.commit();

    }

    public boolean delStuDAO(int stuId) throws Exception {
         DaoStuHandle.start();
        int i = studentDao.deleteData(stuId);
        sqlSession.commit();
        System.out.println("删除了"+i);
        if (i!=0){
          return true;
      }else {
          return false;
      }

    }
    public boolean updateStuDAO(Student student,int id) throws Exception {
        DaoStuHandle.start();
        student.setId(id);
        int i = studentDao.updateData(student);
        System.out.println("更新了 " + i);
        sqlSession.commit();
        if (i!=0){
            System.out.println("更新成功");
        }else{
            System.out.println("更新失败");
        }
        return false;

    }
    public static boolean login(String zh, String pw) throws IOException {

       TestStudentDao.start();
        User login1 = studentDao.findAll1(zh, pw);
        return login1 !=null;
    }
    public void searchStuDAO(Student[] stus, Integer len, Integer a) {
        System.out.println("所查找的学生信息是: " + stus[a]);
    }
}

四、其他层的代码内容:

模型层:

Student:

478a4455084d419fb0023269d32da463.png

User:

954c905861d04f13b0836918deaefe51.png

数据链路层:

124ee6297fe04a278f50faf253c9de6f.png

package ServiceImpl;

import Dao.DaoStuHandle;
import Model.Student;
import Service.StudentService;

import java.util.Scanner;

public class StudentServiceImpl implements StudentService {

    @Override
    public void showStu() throws Exception {
        DaoStuHandle daoStuHandle = new DaoStuHandle();
        daoStuHandle.showStuDAO();
    }

    @Override
    public void addStu(Student student3) throws Exception {
        DaoStuHandle daoStuHandle = new DaoStuHandle();
        daoStuHandle.addStuDAO(student3);
    }

    @Override
    public boolean delStu(int stuId) throws Exception {

//        如果存在,调用数据访问层删除数据
            System.out.println("你确定要删除吗?y or n");
            Scanner scanner = new Scanner(System.in);
            String next = scanner.next();
            if (next.equals("y")){
                DaoStuHandle daoStuHandle = new DaoStuHandle();
                Boolean b = daoStuHandle.delStuDAO(stuId);
                if(b!=null){
                    return true;
                }else{
                    return false;
                }
            }else {
                return false;
            }

    }

    @Override
    public boolean updateStu(Student student,int id) throws Exception {
        if (true){
            DaoStuHandle daoStuHandle = new DaoStuHandle();
            boolean i = daoStuHandle.updateStuDAO(student, id);
            }

        return false;
    }

登录界面的验证码:

package Tools;

import Model.User;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Random;

public class Yanzhengma {
    private Connection connection1;
    public static  ArrayList<User> users=new ArrayList<>();

    public static String code() {
        String ress = "";
        char[] str = {'1', '3', '5', '2', '7', '9', '8', '4', 'r', 'u', 'o', 'p', 'd', 'D', 'Q', 'C'};
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            int anInt = random.nextInt(16);
            ress += str[anInt];
        }
        return ress;
    }

应用层:

package UserView;


import Model.Student;
import ServiceImpl.StudentServiceImpl;

import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class UserUi {

    private Connection connection;
    public static int id =1;
    public void UI() throws Exception {
        StudentServiceImpl studentService = new StudentServiceImpl();

        boolean flag = true;
        while (flag) {
            System.out.println("1.查询所有的学生信息");
            System.out.println("2.添加学生信息");
            System.out.println("3.删除学生信息");
            System.out.println("4.修改学生信息");
            System.out.println("5.查找学生信息");
            System.out.println("0.退出系统");
            Scanner scanner=null;
            int num=0;
            while (true){

                try {
                    System.out.println("亲,输入你所需要的业务序号");
                     scanner = new Scanner(System.in);
                     num = scanner.nextInt();
                     break;
                } catch (Exception e) {
                    System.out.println("请输入正确的业务数字");
                }
            }

            switch (num) {
                case 1:
                    studentService.showStu();
                    break;
                case 2:
                    Student student3 = new Student();
                    System.out.println("请输入你要添加的姓名");
                    String name = scanner.next();
                    System.out.println("请输入你要添加的性别");
                    String sex = scanner.next();
                    System.out.println("请输入你要添加的年龄");
                    int age = scanner.nextInt();
                    System.out.println("请输入你要添加的专业");
                    String major = scanner.next();
                    Date date = new Date();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mmmm-dd hh:mm:ss");
                    String format = simpleDateFormat.format(date);
                    student3.setName(name);
                    student3.setSex(sex);
                    student3.setAge(age);
                    student3.setMajor(major);
                    student3.setTime(format);
                    studentService.addStu(student3);

                    break;
                case 3:
                    System.out.println("请输入你要删除的学号");
                    int stuId = scanner.nextInt();
                    studentService.delStu(stuId);
                    break;
                case 4:
                    Student student = new Student();
                    System.out.println("请输入你修改的id");
                    int id = scanner.nextInt();
                    System.out.println("请输入你修改的姓名");
                    String name1 = scanner.next();
                    System.out.println("请输入你修改的性别");
                    String sex1 = scanner.next();
                    System.out.println("请输入你修改的年龄");
                    int age1 = scanner.nextInt();
                    System.out.println("请输入你修改的专业");
                    String major1 = scanner.next();
                    Date date1 = new Date();
                    SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-mmmm-dd hh:mm:ss");
                    String format1 = simpleDateFormat1.format(date1);
                    student.setName(name1);
                    student.setSex(sex1);
                    student.setAge(age1);
                    student.setMajor(major1);
                    student.setTime(format1);
                    studentService.updateStu(student,id);
                    break;
                case 0:
                    System.out.println("退出系统");
                    flag = false;
                    break;
            }
        }
    }
}

表现层;

import Dao.DaoStuHandle;
import Dao.StudentDao;
import Model.Student;
import Model.User;
import Tools.Yanzhengma;
import UserView.UserUi;
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.InputStream;
import java.util.List;
import java.util.Scanner;

public class StudentRun {
    public static void main(String[] args) throws Exception {
            System.out.println("--------------------------------------");
            System.out.println("**欢迎使用学生信息管理系统***");
            System.out.println("--------------------------------------");
            for (int i = 0; i < 3; i++) {
                System.out.println("请输入管理员的账户和密码");
                Scanner scanner = new Scanner(System.in);
                System.out.println("账户:|");
                String zh = scanner.next();
                System.out.println("密码:|");
                String pw = scanner.next();
                String code = Yanzhengma.code();
                System.out.println("验证码是:(" + code + ")");
                String usercode = scanner.next();
                if (!usercode.equals(code)) {
                    System.out.println("验证码错误");
                } else {
                    DaoStuHandle.start();
                    boolean login2 = DaoStuHandle.findAll1(zh, pw);
                    if (login2){
                      System.out.println("登录成功!");
                      System.out.println("----请选择你的业务操作----");
                      //生成操作界面   用户表现层
                      UserUi userUi = new UserUi();
                      userUi.UI();
                  }else{
                      System.out.println("登录失败,账号或者密码输入错误");
                  }
                }
                if (i==2){
                    System.out.println("账户被锁定请联系相关人员,电话是:19234434652");
                }
            }
    }
}

日志的配置文件内容:

log4j.rootLogger=debug, stdout,R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
Log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
Log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=5
log4j.appender.R.layout=org.apache.log4j.PatternLayout
Log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

数据库的操作:

在数据库中添加对应的数据库和表,随机添加一些信息:

45305cdd41b3414a8fc582a6cf371019.png

23b93c724ea64d62902f587e93b4b41f.png

最终效果:

7f74983211f4461aa65981aa154312c1.png8ed783355502486da0fa2d649a137fe6.png

 

  • 20
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值