MyBatis-01-01-MyBatis Framework Overview & Simple Implementation Demo


MyBatis introduction

  • MyBatis was originally an open source project iBatis of Apache
  • In 2010, the project was migrated from apache software foundation to Google code, and was renamed MyBatis
  • Migrated to GitHub in November 2013
  • MyBatis is a persistence framework that supports custom SQL queries, stored procedures and advanced mapping
  • Compared with traditional JDBC development, MyBatis eliminates almost all manual settings of codes and parameters
  • MyBatis is an ORM framework
  • MyBatis can use XML or annotations for configuration and mapping, it is Entity classes and SQL statements A mapping relationship is established between, and Hibernate is inEntity classes and database tablesEstablished a mapping relationship between.

Hibernate and MyBatis are both persistence frameworks and ORM frameworks. All are simplifying persistence operations.

All programs finally generated by MyBatis are manually generated by programmers.


MyBatis core XML configuration file

The XML configuration file (configuration XML) contains the core settings for the MyBatis system, including the data source (DataSource) for obtaining database connection instances and the transaction manager (TransactionManager) that determines the scope and control method of the transaction.

<?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> 
    <settings>
    	全局参数的设置
        打印SQL语句
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
	多个数据源环境配置
    <environments default="development"> 
        <environment id="development"> 
         	事务和数据源 
        </environment>
    </environments> 
</configuration>

Insert picture description here

Insert picture description here

        <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/mybatis?characterEncoding=utf-8"/>
		        <property name="username" value="root"/>
		        <property name="password" value=""/>
		    </dataSource> 
        </environment>

Insert picture description here

Choosing Managed means that it is managed by the container.
After using Spring, you can use the following types

Insert picture description here
unpooled: No database connection pool, every time a new link is created
pooled: database connection pool, use the link
jndi of the database link pool :

  • UNPOOLED: The implementation of this data source is to simply open and close the connection each time it is requested. It is a bit slow, which is a good choice for simple applications, because it does not require a timely available connection.

  • POOLED: This is the implementation of the data source connection pool of the JDBC connection object, which is used to avoid the necessary initial connection and authentication time when creating a new connection instance. This is a popular method used by current web applications to quickly respond to requests

  • JNDI: This data source is implemented to use containers such as Spring or application servers. The container can configure the data source centrally or externally, and then place a reference to the JNDI context

Insert picture description here

<?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">
    
    <!-- SQL映射文件的配置 -->
    <!-- nameSpace=映射空间。唯一标识的字符串-->
    <mapper namespace="com.mybatis.mapper.UserMapper">
	    <select id="selectAllUsers"    
	            resultType="com.mybatis.entity.User">
	        select * from user
	    </select>
	</mapper>

Insert picture description here


The main class hierarchy of MyBatis

Insert picture description here
SqlSessionFactory: can create Seiion factory class
Executor: dynamic statement generation and cache maintenance

Java data type and jdbc data type comparison table https://blog.csdn.net/qq_43517117/article/details/86551215

Insert picture description here

Insert picture description here

public class MyBatisUtil {
    
    
    private static SqlSessionFactory factory;
    
    //第一次加载时自动执行
    static {
    
    
        try {
    
    
        //参数:主配置文件的文件名。默认路径resources文件目录
            InputStream is = Resources.getResourceAsStream("mybatis.xml");
            factory = new SqlSessionFactoryBuilder().build(is);
            is.close();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
    
    public static SqlSession openSqlSession() {
    
    
        return factory.openSession();
    }
}

The first MyBatis program

manual

Project structure

Insert picture description here

  1. Create a Java Project

  2. Import the jar package required by MyBatis
    Insert picture description here

    One is MyBatis must be packaged. One is the MySql driver package.

  3. Create entity classes and mapper interface (DAO)
    Insert picture description here

Insert picture description here

user.java

package com.mybatis.entity;

public class User {
    
    

	private Integer id;
	private String userName;
	private String password;
	
	
	public Integer getId() {
    
    
		return id;
	}
	public void setId(Integer id) {
    
    
		this.id = id;
	}
	public String getUserName() {
    
    
		return userName;
	}
	public void setUserName(String userName) {
    
    
		this.userName = userName;
	}
	public String getPassword() {
    
    
		return password;
	}
	public void setPassword(String password) {
    
    
		this.password = password;
	}
	
	
	@Override
	public String toString() {
    
    
		return "User [id=" + id + ", userName=" + userName + ", password=" + password + "]";
	}
	
	
	
}

UserMapper.java

package com.mybatis.mapper;

import java.util.List;

import com.mybatis.entity.User;


//类型是interface ,
//这是映射器接口,定义对持久化对象的增删改查方法
//一个映射器接口对应一个映射文件
public interface UserMapper {
    
    

	List<User> findAllUsers();
}

  1. Create the main configuration file mybatis.xml for MyBatis

    Create a new Source Folder in the project and name it resources to store the main configuration file of MyBatis, and create a new XML File in the resources and name it mybatis.xml

MaBatis.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> 


    <!--全局参数的设置,例如日志的实现类 -->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
    
    
    
	<!--多个数据源环境配置,default:下面定义的标签的id-->
    <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/database_mybatis?characterEncoding=utf-8"/>
		        <property name="username" value="root"/>
		        <property name="password" value=""/>
		    </dataSource> 
        </environment>
    </environments> 
    
	<!-- SQL映射文件 -->
	<mappers>
		<mapper resource="com/mybatis/mapper/UserMapper.xml"/>
	</mappers>
    
    
</configuration>
  1. Create SQL mapping XML file for MyBatis

    Create the SQL mapping XML file of MyBatis, and the mapping file should be in the same package as the mapper interface just created, and the name of the mapper interface is the same, so the mapping file name is UserMapper.xml

    Note: To associate the mapping file to the main configuration file

UserMapper.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">
    
    
<!-- 映射文件 -->    
<!-- nameSpace为唯一标识,映射器接口的全限定名 -->
<mapper namespace="com.mybatis.mapper.UserMapper">
	
	<!-- select用来映射查询语句
		id=对应的映射器接口的方法名
		resultType同映射接口中该方法的返回值类型一致,或跟返回值中元素类型一致 
		因为没有声明文件位置,所以参数需要输入全部包名-->
	<select id="findAllUsers" resultType="com.mybatis.entity.User">
		select * from mybatis_01_01_user
	</select>
	
	<select id=""></select>
</mapper>
  1. Associate the SQL mapping file with the main configuration file

Insert picture description here
Add code in the MyBatis.xml file
Insert picture description here

	<!-- SQL映射文件 -->
	<mappers>
		<mapper resource="com/mybatis/mapper/UserMapper.xml"/>
	</mappers>
  1. Write code to test

Insert picture description here

Test.java

package com.mybatis.ui;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.mybatis.entity.User;
import com.mybatis.mapper.UserMapper;
import com.mybatis.util.MyBatisUtil;

public class Test {
    
    

	public static void main(String[] args) {
    
    
		System.out.println("=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
		//创建SqlSession对象
		SqlSession session = MyBatisUtil.openSqlSession();
		//映射器接口权限定名+方法名(映射文件的nameSpace的数值+某一条SQL语句映射的id属性的值)
		//方式1,调用SqlSession的方法
		System.out.println("-=---------------------");
		List<User> users = session.selectList("com.mybatis.mapper.UserMapper.findAllUsers");
		System.out.println(users);
		session.close();
	}
}

Insert picture description here

Test.java

package com.mybatis.ui;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.mybatis.entity.User;
import com.mybatis.mapper.UserMapper;
import com.mybatis.util.MyBatisUtil;

public class Test {
    
    

	public static void main(String[] args) {
    
    
		//方式2:更推荐
		//参数=映射器接口的类型,
		//返回值=该接口实现类型对象
		SqlSession session = MyBatisUtil.openSqlSession();
		UserMapper userMapper = session.getMapper(UserMapper.class);
		List<User> users = userMapper.findAllUsers();
		System.out.println(users);
		
		System.out.println("----------------------------");
		session.close();
	}
}

SqlSession workflow

Insert picture description here
The operation of the transaction is put here

Insert picture description here

The SQL statement can be located through the unique id
Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44627608/article/details/115341805