You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求提供Spring Boot + MyBatis + MyBatis Generator项目搭建完整教程

Hey Danny, let’s walk through a complete, step-by-step MyBatis setup from scratch that should resolve your issues and get your project running smoothly. I’ll use Maven for dependency management (the most widely adopted choice) — if you’re using Gradle, I can tweak the steps later, but let’s start with Maven first.


1. Start with a Fresh Maven Project

First, create a new Maven project. If you’re using an IDE like IntelliJ or Eclipse, select the "Maven Archetype" option and pick maven-archetype-quickstart to get a basic project structure. Alternatively, you can manually create a pom.xml file in an empty folder with this base setup:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>mybatis-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- MyBatis core dependency (stable version as of 2024) -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.13</version>
        </dependency>
        <!-- MySQL JDBC driver (swap for PostgreSQL/Oracle if needed) -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
            <scope>runtime</scope>
        </dependency>
        <!-- JUnit for testing -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <!-- Ensure MyBatis XML files are included in the final build -->
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>

Pro tip: Always use the latest stable versions of dependencies — you can check MyBatis’s official docs for updates, but the versions above work reliably for most use cases.


2. Create MyBatis Core Configuration File

In src/main/resources, make a file named mybatis-config.xml. This is where you’ll set up database connections, transaction rules, and mapper scanning:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- Enable console logging to see generated SQL (super helpful for debugging) -->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <!-- Shorten entity class names for use in XML -->
    <typeAliases>
        <package name="com.example.entity"/>
    </typeAliases>

    <!-- Database environment setup -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/your_db_name?useSSL=false&serverTimezone=UTC"/>
                <property name="username" value="your_db_username"/>
                <property name="password" value="your_db_password"/>
            </dataSource>
        </environment>
    </environments>

    <!-- Tell MyBatis where to find your mapper interfaces/XML files -->
    <mappers>
        <package name="com.example.mapper"/>
    </mappers>
</configuration>

Don’t forget to replace your_db_name, your_db_username, and your_db_password with your actual MySQL credentials. Also, ensure your database has the table you want to work with (we’ll use a user table as an example).


3. Create an Entity Class

Make a package com.example.entity and add a User class that maps directly to your database table:

package com.example.entity;

public class User {
    private Integer id;
    private String username;
    private String email;

    // Getters and setters
    public Integer getId() { return id; }
    public void setId(Integer id) { this.id = id; }
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }

    // Optional: toString() for debugging
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

Corresponding MySQL table (run this in your database):

CREATE TABLE user (
    id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(50) NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL
);

4. Write the Mapper Interface

Create a package com.example.mapper and add a UserMapper interface. This defines the methods you’ll use to interact with the database:

package com.example.mapper;

import com.example.entity.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper // Marks this as a MyBatis mapper interface
public interface UserMapper {
    // Fetch a user by ID
    User selectUserById(Integer id);

    // Insert a new user
    int insertUser(User user);
}

5. Create the Mapper XML File

In src/main/resources, make a folder mapper (match your mapper interface’s package structure) and add UserMapper.xml. This is where you’ll write the SQL for your interface methods:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace must exactly match your mapper interface's full class name -->
<mapper namespace="com.example.mapper.UserMapper">

    <!-- Maps SQL columns to entity fields (optional if names match exactly) -->
    <resultMap id="UserResultMap" type="User">
        <id column="id" property="id"/>
        <result column="username" property="username"/>
        <result column="email" property="email"/>
    </resultMap>

    <!-- Matches the selectUserById method in the interface -->
    <select id="selectUserById" resultMap="UserResultMap">
        SELECT id, username, email FROM user WHERE id = #{id}
    </select>

    <!-- Matches the insertUser method; auto-generates and returns the new user ID -->
    <insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO user (username, email) VALUES (#{username}, #{email})
    </insert>

</mapper>

Critical check: The namespace must match your mapper interface’s full class name, and each id must exactly match the method name in the interface (case-sensitive!).


6. Test the Setup

Create a test class in src/test/java/com/example named MyBatisTest:

package com.example;

import com.example.entity.User;
import com.example.mapper.UserMapper;
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 org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisTest {

    @Test
    public void testMyBatisWorkflow() throws IOException {
        // Load the MyBatis configuration file
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        // Open a session with auto-commit enabled
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            // Get the mapper instance
            UserMapper mapper = session.getMapper(UserMapper.class);

            // Test inserting a user
            User newUser = new User();
            newUser.setUsername("danny_test");
            newUser.setEmail("danny@example.com");
            int rowsInserted = mapper.insertUser(newUser);
            System.out.println("Rows inserted: " + rowsInserted);
            System.out.println("New user ID: " + newUser.getId());

            // Test fetching the inserted user
            User retrievedUser = mapper.selectUserById(newUser.getId());
            System.out.println("Retrieved user: " + retrievedUser);
        }
    }
}

Run this test — if everything is set up correctly, you’ll see console logs showing the generated SQL, and the test will print the inserted user’s details.


7. Quick Fixes for Common Issues

If you still hit roadblocks, check these:

  • Configuration path: Ensure mybatis-config.xml is in src/main/resources (not nested in a subfolder unless you adjust the path in the test).
  • Mapper XML matching: Double-check the namespace and method id in the XML match the interface exactly.
  • Dependency conflicts: Run mvn dependency:tree to check for conflicting versions of MyBatis or JDBC drivers.
  • Database connection: Verify your MySQL server is running, and the URL/username/password in mybatis-config.xml are correct.
  • Mapper scanning: If you don’t use @Mapper on the interface, make sure the mappers section in mybatis-config.xml includes the correct package or XML path.

内容的提问来源于stack exchange,提问作者danny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:13:19