search
HomeJavajavaTutorialGetting Started with MyBatis: Writing a Complete Program Example

Getting Started with MyBatis: Writing a Complete Program Example

Feb 22, 2024 am 08:45 AM
getting StartedmybatisProgram example

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>

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>

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方法
}

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>
  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);
}
  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();
        }
    }
}
  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

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!

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 do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.