Home > Java > javaTutorial > body text

Learn the MyBatis entry program: simply master the key skills

WBOY
Release: 2024-02-18 23:26:06
Original
657 people have browsed it

Learn the MyBatis entry program: simply master the key skills

Teach you step by step how to write a MyBatis introductory program: easily master the core skills

Introduction:
MyBatis is a popular persistence layer framework, which can help us more Interact with the database conveniently. This article will be based on a simple example and teach you step by step how to write an introductory program for MyBatis, allowing you to easily master the core skills. During the writing process, we will use Java as the programming language and the MySQL database as an example.

1. Environment preparation
Before starting, we need to prepare the following environment:

  1. JDK: Make sure that the JDK has been installed and the environment variables have been configured correctly.
  2. Maven: Maven is a tool for building Java projects. We will use Maven to manage our project dependencies.
  3. MySQL database: Make sure that the MySQL database has been installed and the corresponding database and tables have been created.

2. Create a Maven project

  1. Open an IDE (such as Eclipse, IntelliJ IDEA, etc.) and create a new Maven project.
  2. Add MyBatis and MySQL dependencies in the pom.xml file:
<dependencies>
    <!-- MyBatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>
    
    <!-- MySQL -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.22</version>
    </dependency>
</dependencies>
Copy after login

3. Write the database configuration file

  1. In src/main/resources Create a file named mybatis-config.xml in the directory.
  2. Add the following content in mybatis-config.xml:
<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?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai"/>
                <property name="username" value="your_username"/>
                <property name="password" value="your_password"/>
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <mapper resource="mapper/UserMapper.xml"/>
    </mappers>
</configuration>
Copy after login

Pay attention to replacing the value attribute in the <property> tag Information about your own database.

4. Write the POJO class corresponding to the data table

  1. Create a User class to represent the records in the database table.
public class User {
    private int id;
    private String name;
    private int age;
  
      // 省略getter和setter方法
}
Copy after login

2. Write the Mapper interface and mapping file

  1. Create a UserMapper interface to define the method of operating the database.
public interface UserMapper {
    public User getUserById(int id);
    public List<User> getAllUsers();
    public void addUser(User user);
    public void updateUser(User user);
    public void deleteUser(int id);
}
Copy after login
  1. Create a file named UserMapper.xml in the src/main/resources/mapper directory.
  2. Add the following content in 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">
    <select id="getUserById" parameterType="int" resultType="com.example.pojo.User">
        SELECT * FROM user WHERE id = #{id}
    </select>
    
    <select id="getAllUsers" resultType="com.example.pojo.User">
        SELECT * FROM user
    </select>
    
    <insert id="addUser" parameterType="com.example.pojo.User">
        INSERT INTO user (name, age) VALUES (#{name}, #{age})
    </insert>
    
    <update id="updateUser" parameterType="com.example.pojo.User">
        UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}
    </update>
    
    <delete id="deleteUser" parameterType="int">
        DELETE FROM user WHERE id = #{id}
    </delete>
</mapper>
Copy after login

5. Write test code

  1. Create a Java class named App and write Test the code.
public class App {
    public static void main(String[] args) {
        // 创建SqlSessionFactory对象
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        
        // 获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        
        try {
            // 获取UserMapper接口的实例
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            
            // 测试getUserById方法
            User user = userMapper.getUserById(1);
            System.out.println(user.getId() + " " + user.getName() + " " + user.getAge());
            
            // 测试getAllUsers方法
            List<User> userList = userMapper.getAllUsers();
            for (User u : userList) {
                System.out.println(u.getId() + " " + u.getName() + " " + u.getAge());
            }
            
            // 测试addUser方法
            User newUser = new User();
            newUser.setName("张三");
            newUser.setAge(20);
            userMapper.addUser(newUser);
            sqlSession.commit();
            
            // 测试updateUser方法
            User updateUser = new User();
            updateUser.setId(1);
            updateUser.setName("李四");
            updateUser.setAge(25);
            userMapper.updateUser(updateUser);
            sqlSession.commit();
            
            // 测试deleteUser方法
            userMapper.deleteUser(1);
            sqlSession.commit();
        } finally {
            sqlSession.close();
        }
    }
}
Copy after login

6. Run the program

  1. Right-click the App class in the IDE and select "Run As" -> "Java Application" to run the program.
  2. Check the console output to confirm that the program is running normally.

Conclusion:
Through the study of this article, I believe you have easily mastered the core skills of MyBatis. I hope you can use MyBatis in actual projects to improve development efficiency. If you want to further learn the advanced usage of MyBatis, it is recommended to refer to the official documentation and related books for continuous in-depth study and practice. I wish you greater success in your MyBatis learning journey!

The above is the detailed content of Learn the MyBatis entry program: simply master the key skills. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!