Basic tutorial on Java Mybatis framework and basic tutorial on mybatis

Source: Internet
Author: User

Basic tutorial on Java Mybatis framework and basic tutorial on mybatis

1. Introduction to Mybatis

MyBatis is a first-class persistence framework that supports custom SQL, stored procedures, and advanced ing. MyBatis eliminates almost all JDBC code, and does not need to manually set parameters or obtain retrieval results. MyBatis can be configured in a simple XML format or annotation, and can Map basic data elements, Map interfaces, and POJOs (common java object) to records in the database.

2. MyBatis Workflow

(1) load configuration and initialize

Trigger condition: load the configuration file

Configuration comes from two sources: configuration files and Java code annotations, load the SQL configuration information into MappedStatement objects (including input parameter ing configuration, executed SQL statements, and result ing configuration) and store them in the memory.

(2) receive call requests

Trigger condition: Call the API provided by Mybatis

Input parameter: the ID of the SQL statement and the input parameter object.

Process: send the request to the lower-layer Request Processing Layer for processing.

(3) processing operation request trigger condition: the API interface layer transmits the request

Input parameter: the ID of the SQL statement and the input parameter object.

Processing Process:

(A) Find the corresponding MappedStatement object based on the SQL ID.
(B) parse the MappedStatement object based on the input parameter object to obtain the final SQL statement to be executed and execute the input parameter.
(C) obtain the database connection, input parameters to the database for execution based on the obtained final SQL statement and execution, and obtain the execution result.
(D) convert the execution result based on the result ing configuration in the MappedStatement object and obtain the final processing result.
(E) release the connection resource.

(4) return the processing result and return the final processing result

Basic Idea of orm tools

Either hibernate or mybatis, you can have one thing in common:

  • Obtain sessionfactory from the configuration file (usually in the XML configuration file.
  • Sessions generated by sessionfactory
  • Add, delete, modify, and query data and commit transactions in the session.
  • Close the session after it is used up.
  • 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: APIs provided to external users. developers can use these local APIs to manipulate databases. When a call request is received at the interface layer, the data processing layer is called to complete specific data processing.

2. Data Processing Layer: responsible for specific SQL search, SQL parsing, SQL Execution, and execution result ing processing. It mainly aims to complete a database operation based on the called request.

3. Basic Support layer: Responsible for the most basic functional support, including connection management, transaction management, configuration loading, and cache processing. These are all shared items, extract them as the most basic component. It provides the most basic support for the Data Processing Layer on the upper layer.

Multiple driver packages to be added:

Below is a quick start:

The directory is as follows:

Entity 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 + "]";  }}

Usering file UserMapping. xml

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapper PUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <mapper namespace =" com. oumyye. mapping. UserMapping "> <! -- Write the query SQL statement in the select tag and set the id attribute of the select tag to getUser. The id attribute value must be unique, the parameterType attribute cannot be used repeatedly to specify the parameter type used for query. The resultType attribute specifies the type of the returned result set in the query. resultType = "com. oumyye. model. "User" indicates that the query result is encapsulated into an object of the User class. The returned User class is the entity class corresponding to the users table --> <! -- Query by id to obtain a user object --> <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"/> <! -- Configure database connection information --> <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 {@ Testpublic void test () {String resource = "mybatis. xml "; // use the class loader to load the configuration file of mybatis (It also loads the associated ing file) InputStream is = Tests. class. getClassLoader (). getResourceAsStream (resource); // The SqlSessionFactory sessionFactory that constructs the sqlSession = new SqlSessionFactoryBuilder (). build (is); SqlSession session = sessionFactory. openSession ();/*** ing the SQL identity string, * com. oumyye. mapping. userMapping is userMapper. the namespace attribute value of the ER er tag in the xml file. * getUser is the id attribute value of the select tag, you can find the SQL statement to be executed */String statement = "com. oumyye. mapping. userMapping. getUser "; // ing the SQL identity string // execute the query and return the SQL user User = session of a unique user object. selectOne (statement, "1123"); System. out. println (user. toString ());}}

Result:

The above is the basic tutorial on getting started with the Java Mybatis framework. I hope it will be helpful for your learning.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.