MyBatis 注解



  • 注解

    在前面的章节中,我们已经了解了如何使用MyBatis执行CURD操作。在那里,我们使用了一个Mapper XML文件来存储映射的SQL语句,并使用一个配置XML文件来配置MyBatis。
    为了映射SQL语句,MyBatis还提供了注解。因此,本章讨论如何使用MyBatis注解。
    在处理注解时,我们可以使用Java mapper接口来映射和执行SQL查询,而不是配置XML文件。
    假设,我们在MySQL中具有以下employee表:
    
    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`)
    );
    Query OK, 0 rows affected (0.37 sec)
    
    
    假设此表具有两个记录,如下所示-
    
    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类

    POJO类将具有执行所需操作所需的所有方法的实现。 在Student.java文件中将Student类创建为-
    
    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.branch = branch;
          this.percentage = 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;
       }    
      
    }
    
    
  • Student_mapper.java

    这是文件,其中包含映射器接口,我们在其中使用批注而不是XML标签声明映射的语句。对于几乎所有基于XML的映射器元素,MyBatis都提供了注释。以下名为Student_mapper.java的文件包含一个映射器接口。在此文件中,您可以看到对STUDENT表执行CURD操作的注释。
    
    import java.util.List;
    
    import org.apache.ibatis.annotations.*;
    
    public interface Student_mapper {
            
       final String getAll = "SELECT * FROM STUDENT"; 
       final String getById = "SELECT * FROM STUDENT WHERE ID = #{id}";
       final String deleteById = "DELETE from STUDENT WHERE ID = #{id}";
       final String insert = "INSERT INTO STUDENT (NAME, BRANCH, PERCENTAGE, PHONE, EMAIL ) VALUES (#{name}, #{branch}, #{percentage}, #{phone}, #{email})";
       final String update = "UPDATE STUDENT SET EMAIL = #{email}, NAME = #{name}, BRANCH = #{branch}, PERCENTAGE = #{percentage}, PHONE = #{phone} WHERE ID = #{id}";
       
       @Select(getAll)
       @Results(value = {
          @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")
       })
       
       List getAll();
      
       @Select(getById)
       @Results(value = {
          @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")
       })
       
       Student getById(int id);
    
       @Update(update)
       void update(Student student);
    
       @Delete(deleteById)
       void delete(int id);
      
       @Insert(insert)
       @Options(useGeneratedKeys = true, keyProperty = "id")
       void insert(Student student);
    }
    
    
  • Annotations_Example.java文件

    该文件将具有应用程序级逻辑,以将记录插入到Student表中。创建并保存mybatisInsert.java文件,如下所示-
    
    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 Annotations_Example { 
    
       public static void main(String args[]) throws IOException{
          
          Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
          SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);               
          SqlSession session = sqlSessionFactory.openSession();
          session.getConfiguration().addMapper(Student_mapper.class);
          
          Student_mapper mapper = session.getMapper(Student_mapper.class);      
          
          //Create a new student object
          Student student = new Student();
          
          //Set the values      
          student.setName("zara");
          student.setBranch("EEE");
          student.setEmail("zara@gmail.com");
          student.setPercentage(90));
          student.setPhone(123412341);
                
          //Insert student data   
          mapper.insert(student);
          System.out.println("record inserted successfully");
          session.commit();
          session.close();
                            
       }
       
    }
    
    
  • 编译并运行

    这是编译和运行Annotations_Example.java文件的步骤。在继续进行编译和执行之前,请确保已正确设置了PATH和CLASSPATH。
    • 如上所示创建Student.xml。
    • 如本教程的MYBATIS-配置XML章节中所示,创建SqlMapConfig.xml 。
    • 如上所示创建Student.java并进行编译。
    • 如上所示创建Annotations_Example.java并进行编译。
    • 执行Annotations_Example二进制文件以运行程序。
    您将得到以下结果,并且将在STUDENT表中创建一条记录。
    
    $java Annotations_Example
    Record Inserted Successfully
    
    
    如果检查student表,它将显示以下结果-
    
    mysql> select * from student;
    +----+----------+--------+------------+-----------+----------------------+
    | ID | NAME     | BRANCH | PERCENTAGE |   PHONE   |        EMAIL         |
    +----+----------+--------+------------+-----------+----------------------+
    |  1 | Mohammad |  It    |     80     | 900000000 | mohamad123@yahoo.com |
    |  2 | Shyam    |  It    |     75     | 984800000 | shyam@gmail.com      |
    |  3 | Zara     |  EEE   |     90     | 123412341 | zara@gmail.com       |
    +----+----------+--------+------------+-----------+----------------------+
    3 rows in set (0.08 sec)
    
    
    以相同的方式,我们可以使用注释执行更新,删除和读取操作,方法是将Annotations_Example.java的内容替换为下面提到的各个代码片段-
    UPDATE
    
    public static void main(String args[]) throws IOException{
          
       Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
       SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);          
       SqlSession session = sqlSessionFactory.openSession();   
       session.getConfiguration().addMapper(Student_mapper.class);
       Student_mapper mapper = session.getMapper(Student_mapper.class); 
          
       //select a particular student using id               
       Student student = mapper.getById(2);
       System.out.println("Current details of the student are "+student.toString());  
          
       //Set new values to the mail and phone number of the student
       student.setEmail("Shyam123@yahoo.com");
       student.setPhone(984802233);
          
       //Update the student record
       mapper.update(student);
       System.out.println("Record updated successfully");   
       session.commit();   
       session.close();
    
    }       
    
    
    SELECT
    
    public static void main(String args[]) throws IOException{
          
       Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
       SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);          
       SqlSession session = sqlSessionFactory.openSession();
       session.getConfiguration().addMapper(Student_mapper.class);      
       Student_mapper mapper = session.getMapper(Student_mapper.class);
          
       //Get the student details
       Student student = mapper.getById(2);
       System.out.println(student.getBranch());
       System.out.println(student.getEmail());
       System.out.println(student.getId());
       System.out.println(student.getName());
       System.out.println(student.getPercentage());
       System.out.println(student.getPhone());      
       session.commit();
       session.close();
                            
    }
    
    
    DELETE
    
    public static void main(String args[]) throws IOException{
          
       Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
       SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);          
       SqlSession session = sqlSessionFactory.openSession();
       session.getConfiguration().addMapper(Student_mapper.class);
          
       Student_mapper mapper = session.getMapper(Student_mapper.class);
       mapper.delete(2);
       System.out.println("record deleted successfully");
       session.commit();
       session.close();            
                            
    }