Home > Java > javaTutorial > Getting Started with MyBatis: Writing a Complete Program Example

Getting Started with MyBatis: Writing a Complete Program Example

王林
Release: 2024-02-22 08:45:03
Original
849 people have browsed it

Getting Started with MyBatis: Writing a Complete Program Example

MyBatis Getting Started: Writing a Complete Program Example

Introduction:

MyBatis is a very popular Java persistence layer framework. It can interact with the database and provides a flexible and efficient way to access the database. This article will introduce the basic usage and core functions of MyBatis through a complete program example.

  1. Environment setup

First of all, we need to introduce MyBatis related dependencies into the project. Add the following dependencies in the pom.xml file:

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>
    <!--其他依赖 -->
</dependencies>
Copy after login

At the same time, we need to configure MyBatis related information, including database connection information, mapping files, etc. Create a configuration file named mybatis-config.xml in the src/main/resources directory and add the following content:

<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_example"/>
                <property name="username" value="root"/>
                <property name="password" value="password"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/example/mapper/UserMapper.xml"/>
    </mappers>
</configuration>
Copy after login

Note that the database connection information in the above configuration needs to be modified according to the actual situation.

  1. Write data model and mapping files

In order to demonstrate the functionality of MyBatis, we create a class named User and define the corresponding mapping in the UserMapper.xml file relation. Create the following two files in the src/main/java/com/example/model directory:

User.java:

package com.example.model;

public class User {
    private int id;
    private String name;
    private int age;

    // 省略构造函数、getter和setter方法
}
Copy after login

UserMapper.xml:

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper">

    <insert id="insertUser" parameterType="com.example.model.User">
        INSERT INTO user (name, age) VALUES (#{name}, #{age})
    </insert>

    <select id="getUserById" resultType="com.example.model.User">
        SELECT * FROM user WHERE id = #{id}
    </select>

</mapper>
Copy after login
  1. Write Mapper interface

Create an interface named UserMapper in the src/main/java/com/example/mapper directory and define the corresponding methods, as shown below:

package com.example.mapper;

import com.example.model.User;

public interface UserMapper {
    void insertUser(User user);
    User getUserById(int id);
}
Copy after login
  1. Write database operation code

Write database operation code in the main method, including obtaining SqlSessionFactory, creating SqlSession, performing database operations, etc. The specific code is as follows:

package com.example;

import com.example.mapper.UserMapper;
import com.example.model.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public class Main {
    public static void main(String[] args) {
        // 获取MyBatis的配置文件流
        Reader reader;
        try {
            reader = Resources.getResourceAsReader("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        // 创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

        // 创建SqlSession
        try (SqlSession session = sqlSessionFactory.openSession()) {
            UserMapper userMapper = session.getMapper(UserMapper.class);

            // 插入用户数据
            User user = new User();
            user.setName("Tom");
            user.setAge(20);
            userMapper.insertUser(user);
            session.commit();

            // 根据ID查询用户数据
            user = userMapper.getUserById(user.getId());
            System.out.println(user);
        }

        // 关闭输入流
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Copy after login
  1. Example of running the program

Enter the project directory in the command line window and execute the following command to run the program:

mvn clean compile exec:java
Copy after login

After the program runs, a piece of user data will be inserted and the user's information will be queried based on the ID. If everything goes well, the console will output the user's information.

Summary:

Through the above complete program examples, we understand the basic usage and core functions of MyBatis. In actual development, we can write corresponding Mapper interfaces and mapping files according to specific needs, and create SqlSession through SqlSessionFactory for database operations. I believe that through learning and practice, we can better use MyBatis to build an efficient Java persistence layer.

The above is the detailed content of Getting Started with MyBatis: Writing a Complete Program Example. For more information, please follow other related articles on the PHP Chinese website!

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