MyBatis: introduction and first program

MyBatis: introduction and first program

My use environment:

  • jdk 1.8

  • MySql 5.0.8(+Navicat for MySQL)

  • IDEA

  • Maven 3.1.1

1, What is Mybatis?

  • MyBatis is an excellent persistence framework.

  • MyBatis avoids almost all the JDBC code and manual setting of parameters and getting the result set

  • MyBatis can use simple XML or annotation to configure and map native information, and map interface and Java entity class (Plain Old Java Objects, common Java objects) to records in database.

  • MyBatis is an open-source project of apache, ibatis. In 2010, this project was migrated from apache to google code and renamed MyBatis.

  • Moved to Github in November 2013.

  • Official documents of Mybatis: http://www.mybatis.org/mybatis-3/zh/index.html

  • GitHub : https://github.com/mybatis/mybatis-3

    Why Mybatis is needed

    • Mybatis is to help program apes store data in database and get data from database
    • The traditional jdbc operation has a lot of repeated code blocks, such as the encapsulation of data extraction, the establishment of database connection and so on The framework can reduce the repetitive code and improve the development efficiency
    • MyBatis is a semi-automatic ORM framework (object relationship mapping) -- > object relationship mapping
    • All things can be done without Mybatis, but with it, all the implementation will be simpler! There is no difference in technology, only the people who use it
    • Benefits of MyBatis
      • Easy to learn: small and simple in itself. There is no third-party dependence. The simplest installation is just two jar files + several sql mapping files. It is easy to learn and use. Through documents and source code, you can fully grasp its design ideas and implementation.
      • Flexibility: mybatis does not impose any impact on the existing design of the application or database. sql is written in xml for unified management and optimization. Through sql statement, all the requirements of database operation can be satisfied.
      • Decouple sql and program code: separate business logic and data access logic by providing DAO layer to make the system design clearer, easier to maintain and easier to unit test. The separation of sql and code improves maintainability.
      • xml tags are provided to support writing dynamic sql.
    • Use more people, follow the crowd!

2, MyBatis first program

Thought process: build environment - > Import Mybatis - > write code - > test

1. database

Create database properties

Table creation (id auto increment)

insert data

2. Import MyBatis related jar package

Maven dependence

Can be in https://mvnrepository.com Find Maven dependencies.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>mybatis_opendoor</groupId>
    <artifactId>mybatis_opendoor</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <!--data base-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.0.8</version>
        </dependency>
        <!--mybatis frame-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!--juit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
    
    <!--Set up Maven Yes properties and xml Release of documents-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>

Mybatis configuration (Mybatis-config.xml)

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

    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <!---->
                <property name="driver" value="com.mysql.jdbc.Driver"></property>
                <property name="url" value="jdbc:mysql://localhost:3306/qq?characterEncoding=UTF-8"></property>
                <property name="username" value="root"></property>
                <property name="password" value="root"></property>
            </dataSource>
        </environment>
    </environments>
    <!--Import Mapper-->
    <mappers>
        <mapper resource="com/haiyang/kuangjia/dao/UserMapper.xml"></mapper>
    </mappers>
</configuration>

Entity class

public class User {
    private int userid;
    private String name;
    private String pwd;
    }
    //getter and setter,toString

Business interface Dao

package com.haiyang.kuangjia.dao;

import com.haiyang.kuangjia.pojo.User;

import java.util.List;

public interface UserDao {


    List<User> getUserAll();
}

Business Impl (changed to xxxMapper.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="com.haiyang.kuangjia.dao.UserDao">//Interface
<select id="getUserAll" resultType="com.haiyang.kuangjia.pojo.User" >//Entity type
        SELECT * FROM qq.user;//Database name. Table
    </select>
</mapper>

Tool class

package com.haiyang.kuangjia.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 MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {

        try {
            String resource ="Mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

Test class

package com.haiyang.kuangjia.Dao;

import com.haiyang.kuangjia.dao.UserDao;
import com.haiyang.kuangjia.pojo.User;
import com.haiyang.kuangjia.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoTest {
    @Test
    public void Test(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            List<User> userList = userDao.getUserAll();
            for (User user : userList) {
                System.out.println(user);
            }
       sqlSession.close();

    }
}

3. exceptions

There is too much difference between the database and Mybatis Version (modify Maven version)

java.lang.AbstractMethodError: Method com/mysql/jdbc/ResultSet.isClosed()Z is abstract

PS: it's convenient to change Mybatis version on Maven!

Maven static resource filtering problem

When an exception occurs, an error will be reported, because the resources such as properties and xml will be filtered out by Maven at runtime. You can open it in the project structure target and see that there is no corresponding required file.

org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.haiyang.kuangjia.dao.UserDao.getUserById

	at org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:225)
	at org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:48)
	at org.apache.ibatis.binding.MapperProxy.cachedMapperMethod(MapperProxy.java:65)
.........

Add the following in pom.xml to solve this problem.

<build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>
Published 1 original article, praised 0, visited 9
Private letter follow

Tags: Mybatis xml Apache Java

Posted on Tue, 03 Mar 2020 21:29:51 -0800 by blade_922