search
HomeJavajavaTutorialWhat is Mybatis? Introduction to Mybatis related content

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

##Some external properties, these properties can be replacedThe extremely important adjustment settings in Mybatis will change the default behavior of Mybatis. Set an alias for the Java type, which is only related to xml configuration. Mapper, loads the MyBatis mapping file. Plug-in, Mybatis allows users to intercept at a certain point in the mapping.

环境配置

  1. Mybatis可以通过

    配置多种环境,比如开发环境、测试环境和生产环境等。

  2. 不过要记住,尽管可以配置多个环境,但是SqlSessionFactory对象只能加载一个。如果你需要同时连接多个数据库,需要创建多个SqlSessionFactory实例。

事务管理

在 MyBatis来进行事务的设置,其中有两种类型的事务管理器。

  1. JDBC:这个配置就是直接使用了 JDBC 的提交和回滚设置,它依赖于从数据源得到的连接来管理事务范围。

  2. MANAGED:这个配置几乎没做什么。它从来不提交或回滚一个连接,而是让容器来管理事务的整个生命周期(比如 JEE 应用服务器的上下文)。 默认情况下它会关闭连接,然而一些容器并不希望这样,因此需要将 closeConnection 属性设置为 false 来阻止它默认的关闭行为。

<transactionManager type="MANAGED">
    <property name="closeConnection" value="false"/>
</transactionManager>

如果你正在使用 Spring + MyBatis,则没有必要配置事务管理器, 因为 Spring 模块会使用自带的管理器来覆盖前面的配置。

数据源

使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。有三种数据源类型

  1. UNPOOLED:这个数据源的实现只是每次被请求时打开和关闭连接。

  2. POOLED:这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来, 避免了创建新的连接实例时所必需的初始化和认证时间。

  3. JNDI:使用JNDI在外部配置数据源。

properties标签

properties为外部属性,比如数据库连接信息可以配置到一个单独的properties文件中,然后在xml中进行引入。

添加一个db.properties文件

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=root

在mybatis主配置文件中引用

<properties resource="db.properties" />
<environments default="development">
    <environment id="development">
        <transactionManager type="JDBC" />
        <dataSource type="POOLED">
            <property name="driver" value="${driver}" />
            <property name="url" value="${url}" />
            <property name="username" value="${username}" />
            <property name="password" value="${password}" />
        </dataSource>
    </environment>
</environments>

映射器

通常MyBatis中将映射关系(非必须)和SQL语句写入到映射文件中,在配置文件中需要手动进行加载映射文件。加载映射文件使用进行加载。Mybatis中有4种加载方式。

1.使用resource,加载classpath路径进行加载。

<mappers>
    <mapper resource="com/simple/mybatis/entitys/EmployeeMapper.xml"/>
</mappers>

2.使用url路径进行加载。

<mappers>
    <mapper url="file:///var/mappers/AuthorMapper.xml"/>
</mappers>

3.使用calss进行加载,注解方式。

<!– 加载class类-->
<mappers>
    <mapper class="使用注解的全类名"/>
</mappers>

4.使用package进行加载,注解方式。

<!– 加载某个包下的所有class文件-->
<mappers>
    <package name="com.simple.mybatis.entitys"/>
</mappers>

别名的使用

之前,我们在sql映射xml文件中的引用实体类时,resultType需要写上实体类的全类名(包名+类名),如下:

<select id="findAll" resultType="com.simple.mybatis.entitys.Employee">
        select id,last_name AS lastName,email,gender from tal_employee
</select>

在mybatis主配置文件中加入

<typeAliases>
    <typeAlias type=“com.simple.mybatis.entitys.Employee" alias="Employee"/>
</typeAliases>

这样在resultType中就可以直接使用Employee类型了。这个别名是不区分大小写的。

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!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

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

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

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

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

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

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

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

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

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 default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SecLists

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

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

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