[JavaEE case] MYBatis entry program

1. Create a project: Start IntelliJ IDEA, select the "File" → "New" → "Project" option in the toolbar

 

2. Data preparation: Create a database named mybatis in MySQL.

CREATE DATABASE mybatis;

Create a users table in the database 

CREATE TABLE users(
	uid int primary key auto_increment,
	uname varchar(20) not null,
	uage int not null
);

And insert a few pieces of test data

INSERT INTO users(uid,uname,uage) VALUES(null,'张三',20),(null,'李四',18);

3. Introduce related dependencies: import MySQL driver package, JUnit test package, MyBatis core package and other related dependencies in the pom.xml file of the project.  

<?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>org.mybatis</groupId>
    <artifactId>MyBatisTest</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.11</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>

4. Create a POJO entity: Create a User class under the com.itheima.pojo package, which is used to encapsulate the properties of the User object.

package com.itheima.pojo;

public class User {
    private int uid;
    private String uname;
    private int uage;

    public int getUid() {
        return uid;
    }
    public void setUid(int uid) {
        this.uid = uid;
    }
    public String getUname() {
        return uname;
    }
    public void setUname(String uname) {
        this.uname = uname;
    }
    public int getUage() {
        return uage;
    }
    public void setUage(int uage) {
        this.uage = uage;
    }
}

5. Create a mapping file UserMapper.xml: This file is mainly used to configure the mapping between SQL statements and Java objects.

<?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为映射的根节点-->
<!--mapper为映射的根节点,namespace指定Dao接口的完整类名
    mybatis会依据这个接口动态创建一个实现类去实现这个接口,
    而这个实现类是一个Mapper对象-->
<mapper namespace="com.itheima.pojo.User">
    <!--id="接口中的方法名"
    parameterType="传入的参数类型"
    resultType="返回实体类对象,使用包.类名"-->
    <select id="findById" parameterType="int"
            resultType="com.itheima.pojo.User">
        select * from users where uid = #{id}
    </select>
</mapper>

6. Create the database connection information configuration file db.properties: configure the parameters of the database connection in this file.

mysql.driver=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&\
  characterEncoding=utf8&useUnicode=true&useSSL=false
mysql.username=root
mysql.password=root

7. Create the core configuration file mybatis-config.xml of MyBatis: This file is mainly used for the environment configuration of the project.

<?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>
    <!--环境配置-->
    <!--加载类路径下的属性文件-->
    <properties resource="db.properties"/>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <!--数据库连接相关配置,db.properties文件中的内容-->
            <dataSource type="POOLED">
                <property name="driver" value="${mysql.driver}"/>
                <property name="url" value="${mysql.url}"/>
                <property name="username" value="${mysql.username}"/>
                <property name="password" value="${mysql.password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--mapping文件路径配置,用于将UserMapper.xml映射文件加载到程序中-->
    <mappers>
        <mapper resource="Mapper/UserMapper.xml"/>
    </mappers>

</configuration>

8. Write test class

package Test;
import com.itheima.pojo.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 org.junit.Test;
import java.io.IOException;
import java.io.Reader;

public class UserTest {
    @Test
    public void userFindByTest() {
        String resources = "mybatis-config.xml";
        //创建流
        Reader reader = null;
        try {
            //读取mybatis-config.xml文件内容到reader对象中
            reader = Resources.getResourceAsReader(resources);
        }catch (IOException e) {
            e.printStackTrace();
        }
        //初始化MyBatis数据库,创建SqlSessionFactory类的实例
        SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
        //创建SqlSession实例
        SqlSession session = sqlMapper.openSession();
        //传入参数查询,返回结果
        User user = session.selectOne("findById",1);
        //输出结果
        System.out.println("\n"+user.getUname());
        //关闭session
        session.close();
    }
}

9. Running results

Guess you like

Origin blog.csdn.net/weixin_66697650/article/details/129463483