Mybatis

1. 实验目的

通过修改实例,学习Mybatis的增删改查功能。

2. 实验环境

项目管理:Maven 示例项目:MyBatisDemo IDE: Eclipse ,IDEA 数据库:MySql , H2, SQLite (三种选一种就可以)

3. 实验要求

MyBatisDemo示例项目使用MyBatis对数据表country进行增删改查。请修改这一示例,使其对数据表 student进行增删改查。以压缩包的形式提交修改好的项目文件压缩包(文件命名规则为:学号+姓名.rar 或 zip )。

4. 实验步骤

1. 首先在数据库中创建数据表student (id,studentID,studentName,studentClass)

2. 修改mybatis-config.xml中数据库的配置:

 1 <properties resource="MySQL8.properties" />  

3. 修改数据库配置文件:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mysql
useUnicode=true&characterEncoding=UTF-8
username=root
password=123456

4.项目文件

mybatis配置:

<?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>

<!--mybatis配置文件的标签顺序必须是以下顺序:
The content of element type “configuration” 
must match “(properties?,settings?,typeAliases?,
typeHandlers?,objectFactory?,objectWrapperFactory?,
reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?)”.
-->

<!-- <properties resource="H2Config.properties" /> -->
  <properties resource="MySQL8.properties" /> 
<!-- <properties resource="SQLiteConfig.properties" /> -->

<settings>
<setting name="logImpl" value="LOG4J"/> 
<setting name="cacheEnabled" value="true"/>
</settings>
 
<typeAliases>
  <package name="cn.edu" />
</typeAliases>

  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>       
      </dataSource>
    </environment>
  </environments>
  
  <mappers>
    <!--  <mapper resource="cn/edu/CountryMapper.xml"/>  -->
       
    <!-- 包下的所有映射器 -->
    <package name="cn.edu" />
  </mappers>
  
</configuration>

javabean:

package cn.edu;

public class Student {
    private long id;
    private int studentID;
    private String studentName;
    private String studentClass;

    public Student() {

    }


    public Student(long id, int studentID, String studnetName, String studnetClass) {
        this.id = id;
        this.studentID = studentID;
        this.studentName = studnetName;
        this.studentClass = studnetClass;
    }

    public long getId() {
        return id;
    }

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

    public int getStudentID() {
        return studentID;


    }

    public void setStudentID(int studentID) {
        this.studentID = studentID;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studnetName) {
        this.studentName = studnetName;
    }

    public String getStudentClass() {
        return studentClass;
    }

    public void setStudentClass(String studnetClass) {
        this.studentClass = studnetClass;
    }
}

接口类:

package cn.edu;

import java.util.List;

public interface StudentMapper {
    //查询所有记录,对应CountryMapper.xml中的id="selectAll"
    public List<Student> selectAll();

    //根据编号查询一条记录,对应CountryMapper.xml中的id="selectOne"
    public Student selectOne(Long id);

    //插入记录,对应CountryMapper.xml中的id="insertCountry"
    public void insertStudent(Student student);

    //更新记录,对应CountryMapper.xml中的id="updateCountry"
    public void updateStudent(Student student);

    //删除记录,对应CountryMapper.xml中的id="deleteCountry"
    public void deleteStudent(Long id);
}

映射器xml:

<?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="cn.edu.StudentMapper">

    <!-- 查询所有记录 -->
    <select id="selectAll" resultType="Student" >
        select id,studentID,studentName,studentClass from student
    </select>

    <!-- 根据编号查询一条记录 -->
    <select id="selectOne" resultType="Student" parameterType="Long">
        select id,studentID,studentName,studentClass from student where id=#{id}
    </select>

    <!-- 插入记录 -->
    <insert id="insertStudent" >
        insert into Student (id,studentID,studentName,studentClass)
        values (#{id},#{studentID},#{studentName},#{studentClass})
    </insert>

    <!-- 更新记录 -->
    <update id="updateStudent">
        update Student set
        id = #{id},
        StudentID = #{studentID},
        StudentName = #{studentName},
        StudentClass=#{studentClass}
        where id = #{id}
    </update>

    <!-- 删除记录 -->
    <delete id="deleteStudent">
        delete from Student where id = #{id}
    </delete>

</mapper>

app:

package cn.edu;

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

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class App {
    
    public static void main(String[] args) throws Exception {
        
        //读取配置文件,并创建Mybatis的SqlSessionFactory对象实例
        InputStream reader = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        reader.close();
        
        // 取得一个SqlSession实例
        SqlSession sqlSession = sqlSessionFactory.openSession();
        
        try {
            // 取得CountryMapper映射器,映射器负责在数据表country与实体类Country之间建立对应关系
            StudentMapper studentmapper = sqlSession.getMapper(StudentMapper.class);

            //List<Country> countryList = sqlSession.selectList("selectAll");
            
            // 查询country表中的所有记录
            showAll(studentmapper);

            // 显示country表中指定的记录
            Scanner scanner = new Scanner(System.in);
            System.out.print("请输入记录的ID号:");
            Long id = scanner.nextLong();
            Student student = (Student) studentmapper.selectOne(id);
            System.out.println(
                    "test:" + student.getId() + " " + student.getStudentID() + " " + student.getStudentName()+" "+student.getStudentClass());

            // 向country表中插入一条记录
            System.out.print("增加一条新的记录,按照<编号,学号,姓名,班级>输入,以逗号分隔:");
            String country_input = scanner.next();
            System.out.println(country_input);
            String[] country_list = country_input.split(",");

            Student country_new = new Student();
            country_new.setId(Long.parseLong(country_list[0]));
            country_new.setStudentID(Integer.parseInt(country_list[1]));
            country_new.setStudentClass(country_list[2]);
            country_new.setStudentClass(country_list[3]);
            studentmapper.insertStudent(country_new);
            sqlSession.commit(); // 不要忘记提交            
            showAll(studentmapper);
            
            //刪除一条记录
            System.out.print("请输入删除记录的ID号:");
            id = scanner.nextLong();
            studentmapper.deleteStudent(id);
            sqlSession.commit(); // 不要忘记提交
            showAll(studentmapper);
            
            //更新一条记录
            System.out.print("请输入更新学生的ID号:");
            id = scanner.nextLong();
            System.out.print("请输入更新学生的学号:");
            int ID = scanner.nextInt();
            System.out.print("请输入新的学生名字:");
            String name = scanner.next();
            System.out.print("请输入新的学生班级:");
            String code = scanner.next();
            
            country_new.setId(id);
            country_new.setStudentID(ID);
            country_new.setStudentName(name);
            country_new.setStudentClass(code);
            
            studentmapper.updateStudent(country_new);;
            sqlSession.commit(); // 不要忘记提交
            showAll(studentmapper);
            
            

        } finally {
            sqlSession.close();
        }

    }
    
    // 查询country表中的所有记录
    private static void showAll(StudentMapper studentmapper) {
        List<Student> studentList = studentmapper.selectAll();
        System.out.println("id" + " 学号 " + " 姓名 "+" 班级");
        for (Student student : studentList)
            System.out.println(student.getId() + " "
                             + student.getStudentID() + " "
                             + student.getStudentName()+" "
                    +student.getStudentClass());
    }
}

5. 运行方法:

mvn package
cd target 
java -jar MyBatisDemo-1.0-SNAPSHOT.jar

6.运行截图

Mybatis

 

7.遇到的错误

1.

Mybatis

 

 注意后面不能有空格。(非常坑)

2.拼写错误

 

上一篇:【Java数据结构】 二叉树经典OJ面试题——刷题笔记+解题思路


下一篇:【Java数据结构】手动实现——栈 和 队列