MyBatis 更新操作



  • 更新操作

    在上一章中,我们讨论了如何使用MyBatis对表执行读操作。本章说明如何使用表来更新表中的记录。
    我们在MySQL中有以下student表-
    
    CREATE TABLE details.student(
       ID int(10) NOT NULL AUTO_INCREMENT,
       NAME varchar(100) NOT NULL,
       BRANCH varchar(255) NOT NULL,
       PERCENTAGE int(3) NOT NULL,
       PHONE int(11) NOT NULL,
       EMAIL varchar(255) NOT NULL,
       PRIMARY KEY (`ID`)
    );
    
    
    假设此表具有两个记录,如下所示-
    
    mysql> select * from STUDENT;
    +----+----------+--------+------------+-----------+--------------------+
    | ID |   NAME   | BRANCH | PERCENTAGE |   PHONE   |      EMAIL         |
    +----+----------+--------+------------+-----------+--------------------+
    | 1  | Mohammad |   It   |     80     | 984803322 | Mohammad@gmail.com |
    | 2  | shyam    |   It   |     75     | 984800000 | shyam@gmail.com    |
    +----+----------+--------+------------+-----------+--------------------+
    
    
  • Student POJO类

    要执行更新操作,您需要将Student.java文件修改为-
    
    public class Student {
    
       private int id;
       private String name;
       private String branch;
       private int percentage;
       private int phone;
       private String email;
    
       public Student(int id, String name,  String branch, int percentage, int phone, String email) {
          super();
          this.id = id;
          this.name = name;
          this.setBranch(branch);
          this.setPercentage(percentage);
          this.phone = phone;
          this.email = email;
       }
            
       public Student() {}
    
       public int getId() {
          return id;
       }
            
       public void setId(int id) {
          this.id = id;
       }
            
       public String getName() {
          return name;
       }
            
       public void setName(String name) {
          this.name = name;
       }
            
       public int getPhone() {
          return phone;
       }
            
       public void setPhone(int phone) {
          this.phone = phone;
       }
            
       public String getEmail() {
          return email;
       }
            
       public void setEmail(String email) {
          this.email = email;
       }
    
       public String getBranch() {
          return branch;
       }
    
       public void setBranch(String branch) {
          this.branch = branch;
       }
    
       public int getPercentage() {
          return percentage;
       }
    
       public void setPercentage(int percentage) {
          this.percentage = percentage;
       }
            
       public String toString(){
          StringBuilder sb = new StringBuilder();
                    
          sb.append("Id = ").append(id).append(" - ");
          sb.append("Name = ").append(name).append(" - ");
          sb.append("Branch = ").append(branch).append(" - ");
          sb.append("Percentage = ").append(percentage).append(" - ");
          sb.append("Phone = ").append(phone).append(" - ");
          sb.append("Email = ").append(email);
                    
          return sb.toString();
       }
            
    }
    
    
  • Student.xml文件

    要使用MyBatis定义SQL映射语句,我们将在Student.xml中添加<update>标记,并在该标记定义内,我们将定义一个“id”,该ID将在mybatisUpdate.java文件中用于对数据库执行SQL UPDATE查询。
    
    <?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 = "Student">    
       <resultMap id = "result" type = "Student">
          <result property = "id" column = "ID"/>
          <result property = "name" column = "NAME"/>
          <result property = "branch" column = "BRANCH"/>
          <result property = "percentage" column = "PERCENTAGE"/>
          <result property = "phone" column = "PHONE"/>
          <result property = "email" column = "EMAIL"/>
       </resultMap>
        
       <select id = "getById" parameterType = "int" resultMap = "result">
          SELECT * FROM STUDENT WHERE ID = #{id};
       </select>
            
       <update id = "update" parameterType = "Student">
          UPDATE STUDENT SET NAME = #{name}, 
             BRANCH = #{branch}, 
             PERCENTAGE = #{percentage}, 
             PHONE = #{phone}, 
             EMAIL = #{email} 
          WHERE ID = #{id};
       </update>
            
    </mapper>
    
    
  • mybatisUpdate.java文件

    该文件具有应用程序级逻辑,可将记录更新到Student表中-
    
    import java.io.IOException;
    import java.io.Reader;
    
    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 mybatisUpdate { 
    
       public static void main(String args[]) throws IOException{
          
          Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
          SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);               
          SqlSession session = sqlSessionFactory.openSession();
          
          //select a particular student using id            
          Student student = (Student) session.selectOne("Student.getById", 1);
          System.out.println("Current details of the student are" );
          System.out.println(student.toString());  
          
          //Set new values to the mail and phone number of the student
          student.setEmail("mohamad123@yahoo.com");
          student.setPhone(90000000);
          
          //Update the student record
          session.update("Student.update",student);
          System.out.println("Record updated successfully");   
          session.commit();   
          session.close();    
              
          //verifying the record 
          Student std = (Student) session.selectOne("Student.getById", 1);
          System.out.println("Details of the student after update operation" );
          System.out.println(std.toString());   
          session.commit();   
          session.close();
                            
       }
    }
    
    
  • 编译并运行

    这是编译和运行mybatisUpdate.java的步骤。在继续进行编译和执行之前,请确保已正确设置了PATH和CLASSPATH。
    • 如上所示创建Student.xml。
    • 如本教程的MYBATIS-配置XML章节中所示,创建SqlMapConfig.xml 。
    • 如上所示创建Student.java并进行编译。
    • 如上所示创建mybatisUpdate.java并进行编译。
    • 执行mybatisUpdate二进制文件以运行程序。
    您将得到以下结果。您可以最初查看特定记录的详细信息,并且该记录将在student表中进行更新,之后,您还可以查看更新后的记录。
    
    Current details of the student are
    Id = 1 - Name = Mohammad - Branch = It - Percentage = 80 - Phone = 984802233 - Email = mohammad@gmail.com
    Record updated successfully
    Details of the student after update operation
    Id = 1 - Name = Mohammad - Branch = It - Percentage = 80 - Phone = 90000000 - Email = mohamad123@yahoo.com
    
    
    如果检查student表,它将显示以下结果-
    
    mysql> select * from student;
    +----+----------+--------+------------+-----------+----------------------+
    | ID |  NAME    | BRANCH | PERCENTAGE |  PHONE    |       EMAIL          |
    +----+----------+--------+------------+-----------+----------------------+
    | 1  | Mohammad |  It    |     80     |  90000000 | mohamad123@yahoo.com |
    | 2  | shyam    |  It    |     75     | 984800000 | shyam@gmail.com      |
    +----+----------+--------+------------+-----------+----------------------+
    2 rows in set (0.00 sec)