Mybatis configuration essay (Idea2021)

Keywords: Java MySQL Mybatis

[TOC]

environment

It's not easy to go back to the Java series!

IDEA 2020.2

Maven 3.6x

Window 10

PHP study (providing service environment in Windows (mysql5.7))

reference resources: https://mybatis.org/mybatis-3/zh/getting-started.html (official documents)

Video: station B crazy God

No one is a natural master. Only continuous inner scroll can become a great master! -- Huterox (please call me "scroll God")

What is Mybatis? A one sentence summary of the Model used to operate the database is similar to the orm in Django. However, according to my current experience, the function seems not as smooth as ORM, and to be honest, the configuration of Java is too redundant. It's hard to say that five minutes in the first ten minutes of the project are preparing the project configuration, which is really outrageous for Django. But I can't help it. I have to go both ways. I learned about the development and application of Spring family bucket in detail a few days ago. I really have to say that there are some things in Java. However, I still have to lay a foundation and take SSM first in order to reconstruct the White Hole community in the future! Learning at this stage should not take too much time, In the process of learning, I will constantly compare the differences between the two series and my most intuitive feelings. In the future, when I know the bar, I will have the opportunity to put forward comprehensive and objective suggestions.

Preparation stage

1, Build table

Here, we directly build tables in Dos. The recommended tool mycli is my favorite database auxiliary tool when playing python. The installation is also very simple

pip3 install mycli

Now create a student table

This tool has a command prompt. You don't have to worry about connecting sql statements.

2, Enter IDEA to create Maven project

For creation here, I still refer to the creation structure of mad God, that is, I create a maven project as the parent project and create a child project in it.

Import dependency

Three dependencies are imported here

mysql driver

mybatis

junit

Here is the configuration file under my parent project

  <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>


    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

Configure mybatis dependencies

This is mainly the key for mybatis to deal with the database. This is a bit like registering in ORM, but Django is obviously much simpler.

The naming of the configuration file is not required, but the official documents are also named in this way.

Let's see the current configuration file first

<?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="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/huterox?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="Huterox"/>
                <property name="password" value="yourpassword"/>
            </dataSource>
        </environment>
    </environments>
<!--    <mappers>-->
<!--        <mapper resource="org/mybatis/example/BlogMapper.xml"/>-->
<!--    </mappers>-->
</configuration>

It is filled with my database name and user name.

Next, we need to create a method to read our configuration file (suddenly return the good garbage of AOP realized through configuration file or annotation, and the python decorator plus dictionary file to find out why it is so troublesome to directly start AOP mode)

Our tool class is placed in utls

Tool class codes are as follows

This is a fixed writing method. The official provides two methods, one is to use the configuration file, and the other is pure hand.

I choose the former, simple! And the video is also this.

package com.huterox.utils;

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.IOException;
import java.io.InputStream;

public class ResourseUtils {
    private static  SqlSessionFactory sqlSessionFactory;
    static {
        try {
            String resource = "src/main/resources/mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //Getting sqlsession is similar to pymysql, which helps us operate the database
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

Start writing code

If you want to use it here, you still need to create module s like Django, but here we need to divide it into layers

1. Entity class

2.Dao interface

3. Interface implementation class

It is worthy of being an engineering language, which is to standardize (hereinafter referred to as "bullshit") of course, don't worry, that is, this disgusting bit is still directly connected to the code

An entity class, we have created a package pojo

package com.huterox.pojo;
//Entity class. The variables and fields here are consistent
public class Student {
    private int id;
    private String name;
    private double height;

    public Student() {
    }

    public Student(int id, String name, double height) {
        this.id = id;
        this.name = name;
        this.height = height;
    }

    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 double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", height=" + height +
                '}';
    }
}


II. Prepare interface and configuration files in Dao

The first is to write an interface. The purpose of this interface is to say how we operate the database. This is different from our Django orm. Our ORM has implemented many methods, such as what we do in Django

Student.objects.all()

We list all the objects (in the database)

Now in mybatis, we need to manually implement this process, that is, our foreshadowing is actually to manually implement the corresponding operations. That is, we even have to write sql statements by hand (now I'm a little worried about sql injection. Later, I think it's necessary to take a look at the anti injection work of mybatis. I've seen the ORM, and it's done very well. Basically, it has high protection against injection.)

Interface class:

package com.huterox.dao;

import com.huterox.pojo.Student;

import java.util.List;

//This part is mainly the interface to operate our entity class
public interface StudentMapper {
    List<Student> getStudentList();
}

The configuration file is created directly in the current directory

<?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="com.huterox.dao.StudentMapper">

    <!--sql-->
    <select id="getStudnetList" resultType="com.huterox.pojo.Student">
        select * from huterox.student
    </select>
</mapper>

The truth here is that it's a little different. You have to write sql statements by hand. This is not in the same order of magnitude as ORM. Of course, it's good to review sql by the way!

test

package com.huterox.dao;

import com.huterox.pojo.Student;
import com.huterox.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class StudentMapperTest {
    @Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> studnetList = mapper.getStudnetList();
        for(Student student:studnetList){
            System.out.println(student);
        }
        sqlSession.close();


    }
}

There's nothing to say about this.

That's it. At present, my experience is that it's troublesome to configure handwritten sql. If you write it according to the current method, it's difficult to ensure development efficiency and security!

To tell you the truth, it's no wonder that we need to build a springboot. It's really troublesome to configure it like this. I laughed when I first heard about the framework that will cause program exceptions due to configuration. Of course, it's nothing, just a preliminary understanding. The later additions, deletions, checks and changes are still the same.

Posted by joozt on Wed, 13 Oct 2021 18:08:14 -0700