Home  >  Article  >  Java  >  Beginner's Guide: Start from scratch and learn MyBatis step by step

Beginner's Guide: Start from scratch and learn MyBatis step by step

王林
王林Original
2024-02-19 11:05:061014browse

Beginners Guide: Start from scratch and learn MyBatis step by step

Concise and easy-to-understand MyBatis introductory tutorial: write your first program step by step

MyBatis is a popular Java persistence layer framework that simplifies working with The process of database interaction. This tutorial will show you how to use MyBatis to create and perform simple database operations.

Step One: Environment Setup
First, make sure your Java development environment has been installed. Then, download the latest version of MyBatis and add it to your Java project. You can download the latest version from MyBatis’ official website.

Step 2: Create a database table
Create a sample table in your database to store student information. The structure of the table is as follows:

CREATE TABLE students (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255),
    age INT,
    grade VARCHAR(255)
);

Step 3: Configure MyBatis
Create a configuration file named mybatis-config.xml in your Java project and add the following content :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<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/mydatabase"/>
                <property name="username" value="root"/>
                <property name="password" value="password"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/StudentMapper.xml"/>
    </mappers>
</configuration>

Please make sure to change the URL, username and password to the actual values ​​for your database.

Step 4: Create Mapper interface
Create a StudentMapper.java interface in your Java project to define methods for interacting with the database. The following is a sample code:

import java.util.List;

public interface StudentMapper {

    List<Student> getAllStudents();

    void insertStudent(Student student);

}

Step 5: Write Mapper XML file
Create a file named StudentMapper in the resources/mapper directory of your Java project. xml file and add the following:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.StudentMapper">

    <select id="getAllStudents" resultType="com.example.model.Student">
        SELECT * FROM students
    </select>

    <insert id="insertStudent" parameterType="com.example.model.Student">
        INSERT INTO students (name, age, grade)
        VALUES (#{name}, #{age}, #{grade})
    </insert>

</mapper>

Be sure to change the namespace to the full class name of your Mapper interface.

Step Six: Create Entity Class
Create a Student.java class in your Java project to represent the student's entity. The following is a sample code:

public class Student {

    private int id;
    private String name;
    private int age;
    private String grade;

    // Getters and setters

}

Step 7: Write a test class
Create a test class named Main.java and add the following code:

import com.example.mapper.StudentMapper;
import com.example.model.Student;
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.InputStream;
import java.util.List;

public class Main {

    public static void main(String[] args) throws Exception {
        // 读取MyBatis配置文件
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        // 创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 创建SqlSession对象
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            // 获取Mapper接口的实例
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);

            // 查询所有学生
            List<Student> students = studentMapper.getAllStudents();
            for (Student student : students) {
                System.out.println(student);
            }

            // 插入一个新学生
            Student newStudent = new Student();
            newStudent.setName("张三");
            newStudent.setAge(20);
            newStudent.setGrade("大一");
            studentMapper.insertStudent(newStudent);
            sqlSession.commit();
        }
    }
}

Please make sure to change the package name and class name to the correct values ​​in your actual project.

Step 8: Run the program
Now you can run Main.java and observe the output in the console. You should be able to see the query results and the results of the insert operation.

Summary
Congratulations! You have successfully written your first MyBatis program. In this tutorial, we introduce the basic concepts and usage of MyBatis, and demonstrate how to use MyBatis to perform database operations through a simple sample program. I hope this tutorial will be helpful for you to learn and master MyBatis. Happy coding!

The above is the detailed content of Beginner's Guide: Start from scratch and learn MyBatis step by step. 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