Home  >  Article  >  Java  >  MyBatis Getting Started Guide: Writing Programs from Scratch

MyBatis Getting Started Guide: Writing Programs from Scratch

王林
王林Original
2024-02-22 16:42:03983browse

MyBatis Getting Started Guide: Writing Programs from Scratch

MyBatis Getting Started Guide: Writing Programs from Scratch

Introduction:
MyBatis is an open source persistence layer framework that can help developers simplify database access. process. Compared with traditional ORM frameworks, MyBatis provides a more flexible and efficient database operation method. This article will start from scratch and lead you to get started with the MyBatis framework through specific code examples.

1. Preparation:
Before we start writing the program, we need some preliminary preparations.

1. Environment setup:
First, you need to ensure that the Java Development Kit (JDK) has been installed and the system environment variables have been configured. Then, you can go to the MyBatis official website to download the latest MyBatis framework and extract it to your project directory.

2. Database preparation:
In this article, we will take the MySQL database as an example for demonstration. You need to ensure that the MySQL database has been installed and create a database named "mybatis_demo".

3. Configure MyBatis:
In the MyBatis framework, we need to connect to the database through the configuration file. First, create a file named "mybatis-config.xml" in the root directory of the project and configure the following:

<?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.cj.jdbc.Driver"/>
                 <property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo?serverTimezone=UTC"/>
                 <property name="username" value="your_username"/>
                 <property name="password" value="your_password"/>
             </dataSource>
         </environment>
    </environments>
    <mappers>
         <!-- 在此处添加映射文件 -->
    </mappers>
</configuration>

Please replace "your_username" and "your_password" with your own database user name and password.

2. Write the program:
After completing the preliminary preparation, we can start writing the program.

1. Create a Java entity class:
First, we need to create a Java entity class, corresponding to a table in the database. In this article, we create a Java class named "MyUser", corresponding to the "user" table:

public class MyUser {
    private int id;
    private String name;
    private int age;
 
    // 省略构造方法、getter和setter
}

2. Create a mapping file:
Next, we need to create a mapping file for the entity class , which defines the mapping relationship between Java objects and database tables. Create a file named "MyUserMapper.xml" and make the following configuration:

<?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.MyUserMapper">
    <resultMap id="MyUserMap" type="com.example.entity.MyUser">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
    </resultMap>
 
    <select id="getUserById" resultMap="MyUserMap">
        SELECT * FROM user WHERE id=#{id}
    </select>
 
    <insert id="addUser" parameterType="com.example.entity.MyUser">
        INSERT INTO user(name, age) VALUES (#{name}, #{age})
    </insert>
</mapper>

3. Create an interface:
Then, we need to create a Java interface, which defines the relevant methods for database operations. Create an interface named "MyUserMapper" and configure the following:

public interface MyUserMapper {
    MyUser getUserById(int id);
 
    int addUser(MyUser user);
}

4. Write code:
Next, we can write a program to operate the database. Create a Java class named "Main" and make the following configuration:

public class Main {
    public static void main(String[] args) {
        // 创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
 
        // 创建SqlSession对象
        try(SqlSession session = factory.openSession()) {
            // 创建Mapper对象
            MyUserMapper mapper = session.getMapper(MyUserMapper.class);
 
            // 调用方法进行数据库操作
            MyUser user = mapper.getUserById(1);
            System.out.println(user.getName());
 
            MyUser newUser = new MyUser();
            newUser.setName("NewUser");
            newUser.setAge(20);
            mapper.addUser(newUser);
 
            session.commit();
        }
    }
}

5. Run the program:
Finally, we can run the program and check whether the data in the database is operated correctly.

3. Summary:
Through the above steps, we can see that through the MyBatis framework, we can use simple Java code to complete the operation of the database, while also reducing the cost of interaction with the database. I hope the sample code in this article will be helpful for you to get started with MyBatis. I wish you a happy learning!

The above is the detailed content of MyBatis Getting Started Guide: Writing Programs from Scratch. 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