Home > Java > javaTutorial > body text

Using MyBatis for SQL mapping in Java API development

WBOY
Release: 2023-06-18 08:45:08
Original
1252 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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
}
Copy after login

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);
}
Copy after login

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());
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template