[MyBatis] Mybatis introduction and detailed operation steps

table of Contents

Introduction of Mybatis:

Construction of Mybatis:

Introduction of Mybatis:

     Mybatis belongs to one of the three major frameworks (Spring, SpringMVC, mybatis), and it is also a technology that is often used in the later period. Mybatis is a semi-ORM (object-relational mapping) framework, which internally encapsulates the SQL statement itself that only needs to be paid attention to. , Instead of loading drivers, creating connections, creating statements and other complicated processes like JDBC . Instead, you only need to directly write the original ecological SQL, which can strictly control the execution performance of SQL and has high flexibility.

    Mybatis can use XML or annotations to configure and map native information, and map POJOs (simple Java objects, ordinary JavaBeans) to records in the database , avoiding almost all JDBC code and manual setting of parameters and obtaining result sets. the way.

    Mybatis configures various statements that need to be executed through XML or annotation mode, and generates the final executed SQL statement through the mapping of the java object and the dynamic parameters of the SQL in the statement . Finally, the mybatis framework executes the SQL and maps the result to a java object. return

advantage:

  • Flexible programming, decoupled from program code, supports dynamic SQL, and can be reused
  • Compared with JDBC, eliminate redundant code
  • Strong compatibility
  • Good integration with Spring]
  • Support ORM mapping between objects and databases

Disadvantages:

  • The writing workload of SQL statements is large, and the programmer's SQL statement skills are strictly required
  • SQL statements depend on the database and poor portability (MySQL-->Oracle needs to modify part of the code)

Use occasion:

  • Mybatis focuses on SQL itself and is a flexible DAO layer solution
  • High performance requirements or items that require more changes

Construction of Mybatis:

Mybatis tools:

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 = null ;
    static{
        //初始化sqlSessionFactory对象
        try {
            InputStream is = Resources.getResourceAsStream("SqlSessionConfig.xml");
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 返回sqlSession对象
     * @return
     */
    public static SqlSession getSession(){

        return  sqlSessionFactory.openSession();
    }

    /**
     * 关闭事务
     * @param sqlSession
     */
    public static void close(SqlSession sqlSession){
        sqlSession.commit();//提交
        sqlSession.close();//关闭
    }
}

Mybatis's properties configuration file (db.properties):

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///数据库名
jdbc.username=root
jdbc.password=root

Main configuration file ( SqlSessionConfig.xml ):

The main configuration file is usually no need to change, and the name of the main configuration file needs and tools in 

InputStream is =Resources.getResourceAsStream(" SqlSessionConfig.xml ") ; The parameter names are the same

The main configuration file needs to be placed in the src folder .

<?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>
    <!--配置加载数据源的配置信息-->
    <properties resource="db.properties"></properties>
    <settings>
    <setting name="lazyLoadingEnabled" value="true"></setting>
</settings>
    <!--自定义别名注册器-->
    <typeAliases>
        <!--配置别名(配置实体类名的别名为实体类名) 别名不区分大小写-->
        <package name="com.james.domain"/>
    </typeAliases>
    <!--环境   default="xxx" 默认使用哪个配置-->
    <environments default="development">
        <!--配置第一组环境  id="任意,只要唯一即可"-->
        <environment id="development">
            <!--使用jdbc的事务管理-->
            <transactionManager type="JDBC"/>
            <!--数据源配置  使用的是mybatis的默认数据源 POOLED-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--加载映射文件,使用package配置映射文件,mapper配置文件中的id不需要全限定类名(包名.包名.类名)-->
        <!--<mapper resource="映射文件.xml"/>-->
        <package name="com.james.dao"></package>
    </mappers>
</configuration>

mapper mapping file:

<?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="接口全限定类名">
    <select id="接口的方法名称" resultType="返回值类型">
      select * from tbl_user
    </select>
</mapper>

Note: If the configuration of the mapper tag in the main configuration file is <package name="com.james.dao"></package> , the mapping file needs to be created in the dao folder and the class name in the dao file is the same

UserDao.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.james.dao.UserDao">
    <insert id="save" parameterType="user">
      insert into
      user (id,username,birthday,sex,address)
      VALUES (#{id},#{username},#{birthday},#{sex},#{address})
    </insert>
</mapper>

UserDao:

package com.james.dao;
import com.james.domain.User;
import java.util.List;
public interface UserDao {
    //方法名和UserDao.xml中的id一致
    void save(User user);
}

Other steps of Mybatis test:

  • Introduce jar package, mybatis, mysql driver, log package (under the src folder) [ This step is completed before the configuration file ]
  • Prepare the test class (test)
  • Prepare dao interface (for example, UserDao above)
  • Prepare User class

jar包:

Link: https://pan.baidu.com/s/18YhNAo4zGUaxyrdKvPu7Cw 
Extraction code: kxwz

test class:

package com.james.test;
import com.james.Utils.MybatisUtils;
import com.james.dao.UserDao;
import com.james.domain.User;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.Date;
import java.util.List;

public class mybatis_test {

    //获取代理对象
    SqlSession session = MybatisUtils.getSession();
    @Test
    public void save(){
        //通过getMapper返回动态代理的实现类
        UserDao userDao = session.getMapper(UserDao.class);
        //添加数据
        User user = new User();
        user.setId(4);
        user.setUsername("James");
        user.setBirthday(new Date());
        user.setAddress("天津");
        user.setSex("男");
        //调用方法
        userDao.save(user);
        //调用关闭事务等方法
        MybatisUtils.close(session);
    }

User class:

package com.james.domain;
import java.util.Date;

public class User {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
    //省略get  set  tostring 构造方法
}

sample:

                                                                

Guess you like

Origin blog.csdn.net/weixin_43267344/article/details/108818369