当前位置:网站首页>Getting started with mybaits (including example tutorial and source code)
Getting started with mybaits (including example tutorial and source code)
2022-06-29 13:20:00 【Full stack programmer webmaster】
Preface :mybatis Is an excellent persistence layer framework for excellent stored procedures and advanced mapping . Greatly simplified , Common operations in database operations . The following is an introduction to mybatis Some concepts of eclipse The actual project is built and used on .
One 、mybatis Introduction to the concept of
1.1、 Background introduction
MyBatis Is to support the general SQL Inquire about , Excellent persistence layer framework for stored procedures and advanced mappings .MyBatis Eliminated almost all of them JDBC Manual setting of code and parameters and retrieval of result sets .MyBatis Easy to use XML Or annotations for configuring and raw mapping , The interface and Java Of POJOs(Plain Old Java Objects, ordinary Java object ) Maps to records in the database .
Every MyBatis Applications are mostly using SqlSessionFactory Example of , One SqlSessionFactory Examples can be found in SqlSessionFactoryBuilder get .SqlSessionFactoryBuilder Can be from a xml Configuration file or an instance of a predefined configuration class .
use xml File construction SqlSessionFactory Examples are very simple things . It is recommended to use classpath resources in this configuration (classpath resource), But you can use anything Reader example , Include using a file path or file:// At the beginning url Created instance .MyBatis There is a utility class —-Resources, It has many ways , You can easily load resources from Classpaths and other locations .
1.2、 Overall process
(1) Load configuration and initialize The trigger condition : Load profile take SQL The configuration information is loaded one by one MappedStatement object ( Including the configuration of the input parameter mapping 、 Executive SQL sentence 、 Result mapping configuration ), Stored in memory .
(2) Receive call request The trigger condition : call Mybatis Provided API Pass in the parameter : by SQL Of ID And the incoming parameter object Treatment process : Pass the request to the lower request processing layer for processing .
(3) Process operation request The trigger condition :API The interface layer delivers the request Pass in the parameter : by SQL Of ID And the incoming parameter object Treatment process : (A) according to SQL Of ID Find the corresponding MappedStatement object . (B) Parse according to the passed in parameter object MappedStatement object , Get what's finally to be done SQL And execute the incoming parameters . (C) Get database connection , According to the final result SQL Statement and execute input parameters to database execution , And get the execution result . (D) according to MappedStatement The result mapping configuration in the object transforms the resulting execution result , And get the final result . (E) Release connection resources .
(4) Return the processing result and return the final processing result to .
1.3、 Functional architecture
Explanation of functional architecture : We put Mybatis The functional architecture of is divided into three layers :
(1)API The interface layer : Interface provided for external use API, Developers through these local API To manipulate the database . As soon as the interface layer receives the call request, it will call the data processing layer to complete the specific data processing .
(2) Data processing layer : Be responsible for specific SQL lookup 、SQL analysis 、SQL Execute and execute result mapping processing, etc . Its main purpose is to complete a database operation according to the call request .
(3) Foundation support layer : Responsible for the most basic functional support , Including connection management 、 Business management 、 Configure load and cache handling , These are all common things , Extract them as the most basic components . For the upper layer of data processing layer to provide the most basic support .
1.4、 Framework
Explain the framework :
(1) Load the configuration : Configuration comes from two sources , One is the configuration file , A place is Java Comments on the code , take SQL The configuration information is loaded into a MappedStatement object ( Including the configuration of the input parameter mapping 、 Executive SQL sentence 、 Result mapping configuration ), Stored in memory .
(2)SQL analysis : When API When the interface layer receives the call request , Will receive incoming SQL Of ID And incoming objects ( It can be Map、JavaBean Or basic data type ),Mybatis Will be based on SQL Of ID Find the corresponding MappedStatement, Then according to the parameter object passed in MappedStatement To analyze , After parsing, you can get the final execution SQL Statements and parameters .
(3)SQL perform : Will eventually get SQL And parameters to the database for execution , Get the result of operating the database .
(4) Result mapping : Transform the results of operating the database according to the mapped configuration , It can be converted into HashMap、JavaBean Or basic data type , And return the final result to .
1.5、 dynamic SQL
MyBatis One of the most powerful features is its dynamic statement function . If you used JDBC Or something like a framework , You will understand SQL How painful it is to connect sentence conditions together , Make sure you don't forget the spaces or stay in columns Omit a comma after the column, etc . Dynamic statements can completely solve the pain . Although with dynamic SQL Working together is not about opening a party, however MyBatis It can really pass through any mapping SQL Statement using powerful dynamic SQL To improve these conditions .
dynamic SQL Element for any used JSTL Or something like that XML For people like text processors , Are very familiar . In the previous version , There are many elements to understand and learn , But in MyBatis 3 There are many improvements in , Now there are only about half of the elements left .MyBatis Using a powerful OGNL Expression to eliminate most elements .
Two 、mybatis example
Next mybatis An example of is in eclipse+maven+mysql Written on the basis of , If ape friends , Not built well maven, I haven't even heard of maven Of , So please read the blogger's about maven The article :http://blog.csdn.net/u013142781/article/details/50316383( Including examples ) If mysql If it is not built well , You can read another blog post :http://blog.csdn.net/u013142781/article/details/50300233
1、 Create table , And insert data :
CREATE TABLE `t_user` ( `USER_ID` int(11) NOT NULL AUTO_INCREMENT, `USER_NAME` char(30) NOT NULL, `USER_PASSWORD` char(10) NOT NULL, PRIMARY KEY (`USER_ID`), KEY `IDX_NAME` (`USER_NAME`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD) VALUES (1, 'luoguohui', '123456');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD) VALUES (2, 'zhangsan', '123456');2、 Add package dependencies , My article Maven First love , Created maven project , Now just add the following dependencies :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.luo</groupId>
<artifactId>first_maven_project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<!-- spring Version number -->
<spring.version>3.2.8.RELEASE</spring.version>
<!-- log4j Log file management pack version -->
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<!-- junit Version number -->
<junit.version>4.10</junit.version>
<!-- mybatis Version number -->
<mybatis.version>3.2.1</mybatis.version>
</properties>
<dependencies>
<!-- add to Spring rely on -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Unit test dependency -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- Log file management package -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
<!--spring Unit test dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!--mybatis rely on -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring package -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.0</version>
</dependency>
<!-- mysql Drive pack -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
</dependencies>
</project>3、 The configuration file :
3.1、mybatis Add... Under the package mybatis-config.xml file (mybatis The configuration 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">
<configuration>
</configuration>3.2、properties Add... Under the package jdbc.properties file ( Data source profile ):
jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/luo
jdbc_username=root
jdbc_password=root3.3、mapper It's a bag userMapper.xml The configuration file ( Table 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="com.luo.dao.UserDao">
<!-- Set up domain Class corresponds to the fields of the table in the database , Note the database fields and domain The field names in the class are different , It's important to !-->
<resultMap id="BaseResultMap" type="com.luo.domain.User">
<id column="USER_ID" property="userId" jdbcType="INTEGER" />
<result column="USER_NAME" property="userName" jdbcType="CHAR" />
<result column="USER_PASSWORD" property="userPassword" jdbcType="CHAR" />
</resultMap>
<!-- Query single record -->
<select id="selectUserById" parameterType="int" resultMap="BaseResultMap">
SELECT * FROM t_user WHERE USER_ID = #{userId}
</select>
</mapper>3.4、spring The configuration file application.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- introduce jdbc The configuration file -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:properties/*.properties</value>
<!-- If there are multiple profiles , Just add here -->
</list>
</property>
</bean>
<!-- Configure data sources -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- Don't use properties To configure the -->
<!-- <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/learning" /> <property name="username" value="root" /> <property name="password" value="[email protected]" /> -->
<!-- Use properties To configure the -->
<property name="driverClassName">
<value>${jdbc_driverClassName}</value>
</property>
<property name="url">
<value>${jdbc_url}</value>
</property>
<property name="username">
<value>${jdbc_username}</value>
</property>
<property name="password">
<value>${jdbc_password}</value>
</property>
</bean>
<!-- Automatically scanned all the XxxxMapper.xml Corresponding mapper Interface file , This eliminates the need for manual configuration one by one Mpper It's a mapping of , as long as Mapper Interface classes and Mapper Just map the file . -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.luo.dao" />
</bean>
<!-- To configure Mybatis The file of ,mapperLocations To configure **Mapper.xml file location ,configLocation To configure mybatis-config file location -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
<!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model" /> -->
</bean>
<!-- Automatically scan for comments bean -->
<context:component-scan base-package="com.luo.service" />
</beans>4、 Interface and class configuration :
4.1、com.luo.domain Add below User.java file :
package com.luo.domain;
public class User {
private Integer userId;
private String userName;
private String userPassword;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
}4.2、com.luo.dao Add below UserDao.java file :
package com.luo.dao;
import com.luo.domain.User;
public interface UserDao {
/** * @param userId * @return User */
public User selectUserById(Integer userId);
}4.3、com.luo.service Add below UserService.java Interface and UserServiceImpl Implementation class :
package com.luo.service;
import com.luo.domain.User;
public interface UserService {
User selectUserById(Integer userId);
}package com.luo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.luo.dao.UserDao;
import com.luo.domain.User;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
public User selectUserById(Integer userId) {
return userDao.selectUserById(userId);
}
}5、 unit testing
5.1、com.luo.baseTest Add below SpringTestCase.java:
package com.luo.baseTest;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
// Appoint bean Injected profile
@ContextConfiguration(locations = { "classpath:application.xml" })
// standards-of-use JUnit @RunWith Comment to tell JUnit Use Spring TestRunner
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringTestCase extends AbstractJUnit4SpringContextTests {
}5.2、com.luo.service add to UserServiceTest.java:
package com.luo.service;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.luo.baseTest.SpringTestCase;
import com.luo.domain.User;
public class UserServiceTest extends SpringTestCase {
@Autowired
private UserService userService;
@Test
public void selectUserByIdTest(){
User user = userService.selectUserById(1);
System.out.println(user.getUserName() + ":" + user.getUserPassword());
}
}5.3、 Run unit tests ,UserServiceTest Right click Run As –>Junit Test, Running results :
6、 Example source code download
http://download.csdn.net/detail/u013142781/9374560
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/2306.html Link to the original text :https://javaforall.cn
边栏推荐
- Beifu PLC controls servo through CANopen communication
- Cvpr2022 | panopticdepth: a unified framework for depth aware panoramic segmentation
- Aes-128-cbc-pkcs7padding encrypted PHP instance
- Another "provincial capital university", coming!
- 【云驻共创】工业智慧“大脑”,老厂焕新的加速秘籍
- B+树|MYSQL索引使用原则
- CVPR2022 | 弱监督多标签分类中的损失问题
- 趣谈网络协议(二)传输层
- 倍福TwinCAT配置、调试第三方伺服详细讲解--以汇川IS620N为例子
- Tutorial on building pytoch model from zero (IV) compiling training process -- Parameter Analysis
猜你喜欢

Cnpm reports an error 'cnpm' is not an internal or external command, nor is it a runnable program or batch file

QT custom control: value range

C#线索二叉树的定义

Mirror vulnerability scanner: trivy

Lm07 - detailed discussion on cross section strategy of futures

倍福PLC通过CANOpen通信控制伺服

Install the typescript environment and enable vscode to automatically monitor the compiled TS file as a JS file

Schiederwerk Power Supply repair smps12 / 50 pfc3800 Analysis

Cvpr2022 𞓜 future transformer with long-term action expectation

CVPR 2022 | 未知目标检测模块STUD:学习视频中的未知目标
随机推荐
C#通过中序遍历对二叉树进行线索化
C # indexe l'arbre binaire en traversant l'ordre moyen
Netdata data data persistence configuration
If I am in Shenzhen, where can I open an account? In addition, is it safe to open an account online now?
GEE——美国LANDFIRE火灾数据集
C#实现队列结构定义、入队、出队操作
STK_GLTF模型
C # implements definition, insertion and construction of binary sort tree
bind原理及模拟实现
Windwos10 installing sshd service
LR、CR纽扣电池对照表
Rslo: self supervised lidar odometer (real time + high precision, icra2022)
Hystrix circuit breaker
hutool工具类的学习(持续更新)
从Mpx资源构建优化看splitChunks代码分割
ZALSM_ EXCEL_ TO_ INTERNAL_ Solving the big problem of importing data from table
Netdata mail alarm configuration
B+树|MYSQL索引使用原则
趣谈网络协议(二)传输层
Acwing 234 abandoning testing