Introduction to mybatis framework for java learning

Introduction to mybatis framework for java learning

0x00 Preface

The previous article uses JDBC to connect the database. Although the code is not complex, it is cumbersome. The JDBC template is also used in the connection pool article to simplify the steps of database operation, but the template simply encapsulates JDBC. It is a tool class, not a framework.

0x01 mybatis overview

1. Mybatis is an excellent persistence layer framework based on Java. It encapsulates JDBC internally, so that developers only need to pay attention to the SQL statement itself, and do not need to spend energy to deal with the complicated processes such as loading driver, creating connection and creating statement.

2. Mybatis configures various statements to be executed by means of XML or annotation, and generates the final executed SQL statement by mapping the Java object and the dynamic parameters of SQL in the statement. Finally, the mybatis framework executes SQL, maps the results into Java objects and returns them.

3. The ORM idea is used to solve the problem of entity and database mapping, encapsulate JDBC and shield the underlying access details of JDBC API, so that we can complete the persistence operation of database without dealing with JDBC API.

0x02 mybatis configuration

We set up the mybatis environment in the following steps:

1:创建maven工程并导入坐标

2:创建实体类和dao的接口

3:创建Mybatis的主配置文件
Conifg.xml

4:创建映射配置文件UserDao.xml

Create a maven project and configure POM XML file.

 <packaging>jar</packaging>   //打包方式设置为jar
    <dependencies>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>MysqL</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>

Add the coordinates of the mybatis and MySQL connection driver package.

When finished, create an interface for userdao

package com.test.dao;

import com.test.domain.User;

import java.util.List;

public interface Userdao {
    List<User> findAll();
}

Then you need to create a config XML file to specify the parameters to connect to the database

mapconfig. XML file:

<?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">
<!-- mybatis的主配置文件 -->
<configuration>
    <!-- 配置环境 -->
    <environments default="MysqL">
        <!-- 配置MysqL的环境-->
        <environment id="MysqL">
            <!-- 配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置数据源(连接池) -->
            <dataSource type="POOLED">
                <!-- 配置连接数据库的4个基本信息 -->
                <property name="driver" value="com.MysqL.jdbc.Driver"/>
                <property name="url" value="jdbc:MysqL://localhost:3306/demo"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
    <mappers>
        <mapper resource="com/test/dao/Userdao.xml"/>
    </mappers>
</configuration>

You also have to add a mapping profile

<?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.test.dao.Userdao">

    <select id="findAll" resultType="com.test.domain.User">
        select * from user
    </select>


</mapper>

Here is the completion of the construction. Here are some precautions:

1.创建IUserDao.xml 和 IUserDao.java时名称是为了和我们之前的知识保持一致。
在Mybatis中它把持久层的操作接口名称和映射文件也叫做:Mapper
所以:IUserDao 和 IUserMapper是一样的

2.mybatis的映射配置文件位置必须和dao接口的包结构相同
		
3.映射配置文件的mapper标签namespace属性的取值必须是dao接口的全限定类名

4.映射配置文件的操作配置(select),id属性的取值必须是dao接口的方法名

In this way, we no longer need to create Dao implementation classes to complete JDBC operations. At this point, mybatis is simply configured.

0x02 mybatis use

After mybatis is configured, create a test class to query the information in the database.

To use mybatis:

1.读取配置文件

2.创建sqlSessionFactory工厂

3.创建sqlSession

4.创建Dao接口的代理对象

5.执行dao中的方法

6.释放资源

code:

package com.test;


import com.test.dao.Userdao;
import com.test.domain.User;
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;
import java.util.List;

public class mybatistest {


    public static void main(String[] args)throws Exception {
        //1.读取配置文件
        InputStream in = Resources.getResourceAsStream("mapconfig.xml");
        //2.创建sqlSessionFactory工厂
        sqlSessionFactoryBuilder builder = new sqlSessionFactoryBuilder();
        sqlSessionFactory factory = builder.build(in);
        //3.使用工厂生产sqlSession对象
        sqlSession session = factory.openSession();
        //4.使用sqlSession创建Dao接口的代理对象
        Userdao userDao = session.getMapper(Userdao.class);
        //5.使用代理对象执行方法
        List<User> users = userDao.findAll();
        for(User user : users){
            System.out.println(user.toString());
        }
        //6.释放资源
        session.close();
        in.close();
    }

}

The above is the writing method of configuration XML. I prefer to use annotations for configuration.

Annotation configuration mybatis

We just need to add a select annotation to the interface

package com.test.dao;

import com.test.domain.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface Userdao {
    @Select("select * from user")
    List<User> findAll();
}

In this way, we can delete the userdao XML file.

Using annotation configuration, you also need to modify mapconfig XML configuration original XML configuration:

<mappers>
        <mapper resource="com/test/dao/Userdao.xml"/>
    </mappers>

Replace with:

<mappers>
        <mapper class="com.test.dao.Userdao"/>
    </mappers>

Mapper uses annotations here, and uses class to specify the interface annotated by the select annotation.

0x03 end

This chapter is written first. The next article will continue to update the content of mybatis.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>