The use of SSM|dao in Java learning

Posted by ro1960 on Sat, 25 Dec 2021 06:12:40 +0100

preface

In the use of Mybatis, for database operations, we create a corresponding interface and sql mapping file for each table.

Note that our dao interface is not directly used in the code in the above two articles. The following will introduce two uses of dao interface.

Tip: the following is the main content of this article. The following cases can be used for reference


1, Traditional dao use

1. Review the interface

In java programming language, an interface is an abstract type and a collection of all abstract methods. An interface cannot be inherited and can only be implemented. The class that implements it must implement all the methods in it, otherwise the class must be declared as an abstract class.

2. Create an interface

public Interface Animal{ 
   //Abstract method
   public void eat();
   public void travel();

}

3. Implement the interface and use

public class Cat implements Animal{
 
   public void eat(){
      System.out.println("Mammal eats");
   }
 
   public void travel(){
      System.out.println("Mammal travels");
   } 
}

public class TestInterface{
    public static void main(String args[]){
      MammalInt m = new MammalInt();
      m.eat();
      m.travel();
   }
}

2, Use of traditional dao in Mybatis


1. Create dao implementation class

The code is as follows (example)

/**
 * studentDao Implementation class of
 * */
public class StudentDaoImpl implements StudentDao {

    @Override
    public List<Student> selectStudent() {

        //1. Get SqlSession
        SqlSession sqlSession = Myutils.getSqlSession();
        //2. Create sql
        String sqlId = "com.bjnode.dao.StudentDao"+"."+"selectStudent";
        //3. Execute sql
        List<Student> students =sqlSession.selectList(sqlId);
        //4. Shut down
        sqlSession.close();
        //5. Return results
        return students;
    }

    @Override
    public int insertStudent(Student student) {
        //1. Get SqlSession
        SqlSession sqlSession = Myutils.getSqlSession();
        //2. Create sql
        String sqlId = "com.bjnode.dao.StudentDao"+"."+"insertStudent";
        //3. Execute sql
        int num =sqlSession.insert(sqlId,student);
        //4. Manually commit transactions
        sqlSession.commit();
        //5. Shut down
        sqlSession.close();
        //6. Return results
        return num;
    }
}

2.Junit unit test: directly create Dao implementation class and call database operation method

The code is as follows (example):

public class MybatisTest01 {

    @Test
    public void testSelectStudent() {
        //1. Create implementation class
        StudentDao so = new StudentDaoImpl();
        //2. Call subclass query method
        List<Student> students =so.selectStudent();
        //3. Output results
        for (Student student:students){
            System.out.println(student);
        }
    }

    @Test
    public void testInsertStudent(){
        //1. Create implementation class
        StudentDao so = new StudentDaoImpl();
        //2. Insert
        Student student = new Student();
        student.setAge(21);
        student.setId(2006);
        student.setName("hye");
        student.setEmail("hye@163.com");
        int num = so.insertStudent(student);
        //3. Results
        System.out.println(((num)!=-1)?"Added successfully":"Add failed");
    }

}

3, Dynamic agent dao in Mybatis

1. Now that we have talked about agents, let's introduce the design pattern of dynamic agents

1) what problems can the agent model solve?

In an object-oriented system, direct access to some objects will bring a lot of trouble to users or system structure for some reasons (such as high cost of object creation, security control for some operations, and out of process access). We can add an access layer to this object when accessing this object.

For example: when your beautiful girlfriend wants to have milk tea with her, what we need now is milk tea, so how can we get it? 1, Prepare various materials for making milk tea and make it by yourself; 2, Milk tea shops sell at beautiful prices and beautiful things. In this process, what we really care about is to get the best cup of milk tea, but the first method is obviously very complex and troublesome compared with the second method, so we find the object of the agent, that is, the milk tea shop, and finally get a satisfactory cup of milk tea.

       

2. Implementation steps of design mode

1) create a common interface (Image) between the proxy object and the proxy object to make them have the same behavior

public interface Image {
   void display();
}

2) create a proxied object (RealImage) that implements the interface

public class RealImage implements Image {
 
   //Property privatization
   private String fileName;
 
   //Overload construction method
   public RealImage(String fileName){
      this.fileName = fileName;
      loadFromDisk(fileName);
   }
 
   //Agent's behavior
   @Override
   public void display() {
      System.out.println("Displaying " + fileName);
   }
  
   //Method privatization
   private void loadFromDisk(String fileName){
      System.out.println("Loading " + fileName);
   }
}

3) create a proxy object class (ProxyImage) that implements the interface

public class ProxyImage implements Image{
 
   // Property privatization
   private RealImage realImage;
   private String fileName;
 
   public ProxyImage(String fileName){
      this.fileName = fileName;
   }
 
   @Override
   public void display() {
      //The proxy object is empty, New
      if(realImage == null){
         realImage = new RealImage(fileName);
      }
      //Not empty, call directly
      realImage.display();
   }
}

4) when requested, use {ProxyImage} to obtain the object of {RealImage} class

public class ProxyPatternDemo {
   
   public static void main(String[] args) {
      Image image = new ProxyImage("test_10mb.jpg");
 
      // The image will be loaded from disk
      image.display(); 
      System.out.println("");
      // Images do not need to be loaded from disk
      image.display();  
   }
}

3. Condition analysis of using agent mode in Mybatis

In the traditional dao use method, there are many repeated codes in the code blocks of two different methods in the dao implementation class, but the different places focus on sql statements:

// Query method 
String sqlId = "com.bjnode.dao.StudentDao"+"."+"selectStudent";
// Insertion method
String sqlId = "com.bjnode.dao.StudentDao"+"."+"insertStudent";

Therefore, our sql mapping file connects them through two things, namespace and id:

<mapper namespace="com.bjnode.dao.StudentDao">
    <select id="selectStudent" resultType="com.bjnode.domain.Student">
        select  * from Student
    </select>

    <insert id="insertStudent" >
        insert into Student values(#{id},#{name},#{email},#{age})
    </insert>
</mapper>

Therefore, mybatis thought of creating dao implementation classes according to different strings to complete the creation of sqlSession and database access, and the dynamic agent can be used.

4. Use of dynamic proxy in Mybatis

The core of the dynamic proxy is the getMapper() method of sqlSession. At this time, we do not need to manually create the implementation class. The code is as follows:

 @Test
    public void testSelectStudent() {
        //1. Get sqlSession
        SqlSession sqlSession  = Myutils.getSqlSession();
        //2. Call getMapper to create a subclass
        StudentDao dao = sqlSession.getMapper(StudentDao.class);
        //3. Call the query method of the interface
        List<Student> students =dao.selectStudent();
        //3. Output results
        for (Student student:students){
            System.out.println(student);
        }
    }

summary

This article is a record of the learning process. If there is any improper expression or error, please point it out in the comment area and discuss it together!

Topics: Java Mybatis SQL Back-end