search
HomeJavajavaTutorialUsing MyBatis for SQL mapping in Java API development

Using MyBatis for SQL mapping in Java API development

In Java Web development, we often need to call the database API to read and write data. However, it is very cumbersome to directly use the JDBC (Java Database Connectivity) API for data operations, which requires manually writing SQL statements, processing database connections, result sets, etc. These trivial tasks not only greatly reduce the developer's work efficiency, but also increase the difficulty of code readability and maintainability. Therefore, we need an excellent ORM (Object Relational Mapping) framework to solve these problems.

MyBatis is an excellent ORM framework that allows developers to perform database operations simply and quickly with just a little configuration. The following article will introduce you to the basic operations of using MyBatis for SQL mapping in Java API development.

1. Basic configuration of MyBatis

Before using MyBatis for development, we need to first understand the basic configuration of MyBatis. First, we need to add MyBatis-related dependencies to the project's pom.xml file:

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.6</version>
</dependency>

Then, we need to create a mybatis-config.xml configuration file in the src/main/resources directory to define MyBatis configuration information. Among them, the most important thing is the configuration of the data source. We can configure it in the following way:

<configuration>
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mybatis/mapper/PersonMapper.xml"/>
    </mappers>
</configuration>

Through the above configuration, we configure the connection information of the database and the location of reading the mapping file. Among them, the mapper tag specifies which SQL mapping files we will use. Here we use a PersonMapper.xml mapping file as an example.

2. Define the mapping file of MyBatis

In MyBatis, the writing of SQL statements is implemented through XML files. We need to define a mapping file (such as PersonMapper.xml) to store mapping information between data tables and Java entity classes and related SQL statements.

The following is an example. Suppose we have a Person entity class, which contains three attributes: id, name and age. We need to map it to the person table in the database. Then, we can define the following SQL mapping statements in the PersonMapper.xml file:

<mapper namespace="com.example.mapper.PersonMapper">
    <select id="selectPersonById" parameterType="int" resultType="com.example.model.Person">
        SELECT * FROM person WHERE id = #{id}
    </select>
    <insert id="insertPerson" parameterType="com.example.model.Person">
        INSERT INTO person (id, name, age) VALUES (#{id}, #{name}, #{age})
    </insert>
    <delete id="deletePersonById" parameterType="int">
        DELETE FROM person WHERE id=#{id}
    </delete>
    <update id="updatePerson" parameterType="com.example.model.Person">
        UPDATE person SET name=#{name}, age=#{age} WHERE id=#{id}
    </update>
</mapper>

In the above code, we define four SQL mapping statements, which correspond to query, insert, delete and update the person table. The data. In each SQL mapping statement, we need to specify the type of SQL statement (such as select, insert, delete, update, etc.), and indicate the method name, parameter type, and return value type corresponding to the SQL statement.

3. Use MyBatis for simple data operations

After we define the MyBatis configuration file and SQL mapping file, we can call the corresponding method in the Java code to implement the corresponding The data has been manipulated. Here is an example of querying Person objects based on ID.

1) Define the Person class

Suppose we have a Person entity class, which contains three attributes: id, name and age:

public class Person {
    private int id;
    private String name;
    private int age;
    // getters and setters
}

2) Define the PersonMapper interface

In the PersonMapper interface, we can define methods to add, delete, modify and query the person table, as shown below:

public interface PersonMapper {
    Person selectPersonById(int id);
    void insertPerson(Person person);
    void deletePersonById(int id);
    void updatePerson(Person person);
}

3) Use MyBatis for data operations

In Java code , we can use MyBatis's SqlSessionFactory class to create a SQL session factory object. Through this object, we can get a SQL session object, and then call the object's method to perform data operations. The following is a simple example of querying a Person object based on ID:

SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory factory = builder.build(inputStream);
SqlSession session = factory.openSession();
PersonMapper personMapper = session.getMapper(PersonMapper.class);
Person person = personMapper.selectPersonById(1);
System.out.println(person.getName());

In the above code, we use the SqlSessionFactoryBuilder class to create a SqlSessionFactory object from the mybatis-config.xml file. Then, we created a SqlSession object through the SqlSessionFactory object, and obtained a PersonMapper proxy class object through the getMapper method of the object. Finally, we called the selectPersonById method of the proxy class, obtained the Person object with ID 1, and printed the output. Isn't it very simple?

4. Summary

MyBatis is a very excellent ORM framework. Through its mapping file, we can perform SQL mapping simply and quickly. This article introduces the basic configuration and usage of MyBatis, hoping to help everyone with data operations in Java API development. Of course, there are many other advanced features and optimization techniques using MyBatis, which we will introduce in subsequent articles, so stay tuned!

The above is the detailed content of Using MyBatis for SQL mapping in Java API development. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
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

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools