


Basic Tutorial for Getting Started with Java Mybatis Framework_Basic Knowledge
1. Introduction to Mybatis
MyBatis is a first-class persistence framework that supports custom SQL, stored procedures and advanced mapping. MyBatis eliminates almost all JDBC code, and there is basically no need to manually set parameters and obtain search results. MyBatis can be configured using a simple XML format or annotations, and can map basic data elements, Map interfaces and POJOs (ordinary Java objects) to records in the database.
2. MyBatis workflow
(1) Load configuration and initialize
Trigger condition: Load configuration file
Configuration comes from two places, one is the configuration file, and the other is the annotation of the Java code. The SQL configuration information is loaded into MappedStatement objects (including the incoming parameter mapping configuration, executed SQL statements, and results). mapping configuration), stored in memory.
(2) Receive call request
Trigger condition: Call the API provided by Mybatis
Incoming parameters: SQL ID and incoming parameter object
Processing process: Pass the request to the lower request processing layer for processing.
(3) Process the operation request. Trigger condition: API interface layer passes the request
Incoming parameters: SQL ID and incoming parameter object
Processing process:
(A) Find the corresponding MappedStatement object based on the SQL ID.
(B) Parse the MappedStatement object according to the incoming parameter object to obtain the final SQL to be executed and the execution incoming parameters.
(C) Obtain the database connection, pass in the final SQL statement and execution parameters to the database for execution, and obtain the execution result.
(D) Convert the execution result obtained according to the result mapping configuration in the MappedStatement object, and obtain the final processing result.
(E) Release connection resources.
(4) Return the processing result and return the final processing result
Basic idea of ORM tools
Whether you have used hibernate or mybatis, you can compare them with one thing in common:
- Get sessionfactory. from the configuration file (usually an XML configuration file)
- session generated by sessionfactory
- Complete the addition, deletion, modification, and transaction submission of data in the session.
- Close the session after use.
- There is a mapping configuration file between the java object and the database, which is usually an xml file.
Functional Architecture
The functional architecture of Mybatis is divided into three layers:
1. API interface layer: interface API provided for external use. Developers use these local APIs to manipulate the database. Once the interface layer receives the call request, it will call the data processing layer to complete specific data processing.
2. Data processing layer: Responsible for specific SQL search, SQL parsing, SQL execution and execution result mapping processing, etc. Its main purpose is to complete a database operation according to the calling request.
3. Basic support layer: Responsible for the most basic functional support, including connection management, transaction management, configuration loading and cache processing. These are common things, and they are extracted as the most basic components. Provide the most basic support for the upper data processing layer.
More driver packages need to be added:
Here’s a quick start:
The directory is as follows:
Entity class User
package com.oumyye.model; public class User { private String id; private String name; private int age; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; } }
Mapping file UserMapping.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.oumyye.mapping.UserMapping"> <!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复 使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型 resultType="com.oumyye.model.User"就表示将查询结果封装成一个User类的对象返回 User类就是users表所对应的实体类 --> <!-- 根据id查询得到一个user对象 --> <select id="getUser" parameterType="String" resultType="com.oumyye.model.User"> select * from user where id=#{id} </select> </mapper>
Resource file mybatis.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> <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/mybatis" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <mappers> <mapper resource="com/oumyye/mapping/userMapping.xml"/> </mappers> </configuration>
Test class:
package test; import java.io.InputStream; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import com.oumyye.model.User; public class Tests { @Test public void test(){ String resource = "mybatis.xml"; //使用类加载器加载mybatis的配置文件(它也加载关联的映射文件) InputStream is = Tests.class.getClassLoader().getResourceAsStream(resource); //构建sqlSession的工厂 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession session = sessionFactory.openSession(); /** * 映射sql的标识字符串, * com.oumyye.mapping.UserMapping是userMapper.xml文件中mapper标签的namespace属性的值, * getUser是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL */ String statement = "com.oumyye.mapping.UserMapping.getUser";//映射sql的标识字符串 //执行查询返回一个唯一user对象的sql User user = session.selectOne(statement, "1123"); System.out.println(user.toString()); } }
Result:
The above is a basic tutorial on getting started with the Java Mybatis framework. I hope it will be helpful to everyone's learning.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
