This article brings you what is Mybatis? The introduction of Mybatis related content has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Introduction to MyBatis
MyBatis was originally an open source project iBatis of apache. In 2010, this project was moved from apache software foundation to google code and renamed MyBatis . Migrated to Github in November 2013.
MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures and advanced mapping. MyBatis avoids almost all JDBC code and manual setting of parameters and retrieval of result sets. MyBatis can use simple XML or annotations for configuration and native Maps to map interfaces and Java POJOs (Plain Old Java Objects, ordinary Java objects) into records in the database.
MyBatis reference official website
http://www.mybatis.org/mybatis-3/zh/index.html
MyBatis download address
https://github.com/mybatis/mybatis-3
Advantages of MyBatis
-
Open source excellent persistence layer framework
Separation of SQL statements and code
Configuration-oriented programming
-
Good support for complex data mapping
Dynamic SQL
MyBatis development steps
1. Add the required jar package
1) mybatis-3.3.0 core package (if you need log operation, you can import dependent packages)
2) Database driver (mysql-connector-java-5.1.22-bin)
2. Create a database and add test data
create table `tal_employee` ( `id` int (11), `last_name` varchar (360), `email` varchar (300), `gender` char (9) );
INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('1','韩信','hanxin@gemail.com','男'); INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('2','LiBaihH','libai@gemail.com','男'); INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('3','孙尚香','sunshangxiang@gemail.com','女'); INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('4','安琪拉','anqila@gemail.com','女'); INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('5','Hello','Hello@gemail.com','男'); INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('6','Miya','Miya@gemail.com','男');
3. Create an entity class
public class Employee { private Integer id; private String lastName; private String email; private String gender; //此处省略get set toString。。。 }
4. Create entity class mapping configuration 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="EmployeeMapper"> <!-- 定义一个查询方法 resultType 返回值类型--> <select id="findAll" resultType="com.simple.mybatis.entitys.Employee"> select * from tal_employee </select> </mapper>
5. Create mybatis main 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> <!-- 配置环境 default默认使用环境名字--> <environments default="development"> <!-- 配置一个环境 --> <environment id="development"> <!-- 使用事务JDBC事务管理器 --> <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/simple/mybatis/entitys/EmployeeMapper.xml" /> </mappers> </configuration>
Get SqlSessionFactory object
private SqlSessionFactory sqlSessionFactory; @Before public void init() throws IOException{ //读取mybatis主配置文件 InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); /** * 实例化SqlSessionFactory * 如果没有指定默认环境,可以在这里指定使用的环境ID,比如我先在有个DEV环境 * sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream,"DEV"); * 我这里已经使用了默认环境所以我就不用这种方式创建了 */ sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); }
Access the database
Get the SqlSession object, act on a conversation with the database, act on a conversation with the database
SqlSession session = sqlSessionFactory.openSession();
Get all employee records
EmployeeMapper is the namespace of our entity class mapping file, findAll is the ID of our select tag
List<Employee> employees = session.selectList("EmployeeMapper.findAll"); for (Employee employee : employees) { System.out.println(employee); }
Access results:
Employee [id=1, lastName=null, email=hanxin@gemail.com, gender=男] Employee [id=2, lastName=null, email=libai@gemail.com, gender=男] Employee [id=3, lastName=null, email=sunshangxiang@gemail.com, gender=女] Employee [id=4, lastName=null, email=anqila@gemail.com, gender=女] Employee [id=5, lastName=null, email=Hello@gemail.com, gender=男] Employee [id=6, lastName=null, email=Miya@gemail.com, gender=男]
It is normal for us to access the database here, why is lastName empty? ?
Solution to the mismatch between table fields and class attribute names
Reason: It should be because the attribute on our entity class called lastName does not correspond to the name of the database column last_name, so it is obtained The value is empty
Solution 1: Alias the select tag in the entity class mapping file
<select id="findAll" resultType="com.simple.mybatis.entitys.Employee"> select id,last_name AS lastName,email,gender from tal_employee </select>
Solution 2: Configure camel case naming in the mybatis main configuration file, you need to The configuration is ranked first, otherwise an XML error will be reported
<settings> <!-- 开启驼峰式命名规则 --> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings>
Use option 2 The attribute lastName in our class will match the database field last_name
Use the log to view SQL statements, etc.
First we need to add mybatis dependency package
Add log4j.properties
#设置输出级别和输出位置 log4j.rootLogger=debug,Console #设置控制台相关的参数 log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n #设置MyBatis的输出内容 log4j.logger.java.sql.ResultSet=INFO log4j.logger.org.apache=INFO log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
So that we can use log4j to view our sql statements and incoming parameters. . Wait
MyBatis configuration file
Through the previous simple MyBatis case, you should understand the basic structure of the MyBatis framework, which is the same as Hibernate , MyBatis contains a core configuration file and mapping file.
Core configuration file (mybatis-config.xml): Contains the core configuration of Mybatis, including connection pool information, transactions, loading mapping files, parameter settings and other configurations.
Mapping file (EmployeeMapper.xml): It mainly implements the mapping of entity objects to the database, associations, Sql statements, etc.
Core configuration file
Tag | Description |
---|---|
Configuration environment | |
The above is the detailed content of What is Mybatis? Introduction to Mybatis related content. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software