IDEA uses Maven to deploy the first MyBatis project (super detailed)

         Compared with the traditional way of creating Spring Web in IDEA, it is easier to create MyBatis project with Maven, because you can introduce dependencies through the pom.xml file to avoid problems such as downloading jar packages from the official website.

1. Create a Maven project:

Open IDEA, click File--->New---->Project:

After selecting the project location, it will officially start.

 

2. Import junit, mybatis, and mysql-connector-java dependencies in pom.xml (the least necessary dependencies)

Replace the original pom.xml with the following code. Other blog posts on the Internet also import log dependencies, which is actually unnecessary

<?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>mybatisTest</groupId>
    <artifactId>mybatisTest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>

        <!--mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>

        <!--mysql-connector-java依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>

        <!--junit依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

 

Three, create a table in the mysql database (operation in the cmd command line)

Note: The database name and table name are useful in the code in the MyBatis project, so write them down!

1. Create a database mybatis

命令:create database mybatis;

2. Create a table mybatis under the database mybatis,

Command: use mybatis;//use mybatis database

Command: create table mybatis(

id int,

name varchar(10),

sex varchar(5),

addr varchar(5));

3. Use the insert command to insert the content shown in the figure below

 

Fourth, start code writing in the Maven project

Attach the project directory first: a total of five files need to be written

User.java    userMapper.xml   JDBC.properties   mybatis-config.xml    TestMybatis.java

 

Tips: There is a detailed introduction on how to create the first Mybatis project in the official mybatis document, although it is a test of English.

Link: https://mybatis.org/mybatis-3/getting-started.html

 

The blogger will write each document in the order of the official document!

1. Create a mybatis-config.xml file in the resources directory

The value="${}" part of <property> is an EL expression, and its value is mapped from JDBC.properties

<?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="JDBC.properties"/>

    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--将写好的userMapper.xml映射文件注册到全局配置文件mybatis-config.xml中-->
    <mappers>
        <mapper resource="Mapper/userMapper.xml"/>
    </mappers>

</configuration>

2. Create a JDBC.properties file in the resources directory (its value is mapped to the mybatis-config.xml file)

username and password are the username and password when connecting to MySQL

Note: The following localhost:3306/+ database name ?serverTimezone, if you create the database, the database name is not mybatis, then you must change it accordingly! !

Otherwise there will be an exception

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai
username=*******
password=******

3. Create a JavaBean file

Create User.java file under main/java/cn.mybatis.bean

package cn.mybatis.bean;
public class User {
    private Integer id;
    private String name;
    private String sex;
    private String addr;

    public User() {
    }

    public User(Integer id, String name, String sex, String addr) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.addr = addr;
    }

    public int getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", addr='" + addr + '\'' +
                '}';
    }
}

 

4. Create SqlSessionFactory from the XML file (ie mybatis-config.xml)

Attach the official website description:

Probably meaning: every MyBatis application revolves around an instance of SqlSessionFactory. You can use the SqlSessionFactory builder to obtain an instance of SqlSessionFactory.

So create a new TestMybatis.java test file under test/java/cn.mybatis

package cn.mybatis;

import cn.mybatis.bean.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.InputStream;

public class TestMybatis {
    @Test   //注意一定要写此注解表示是测试类
    public void init() throws IOException {
        String resource = "mybatis-config.xml";//通过流处理获取sqlSessionFactory创建一个实例
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession session = sqlSessionFactory.openSession();//获取SqlSession实例
        Integer id = 1;// 在数据库中取哪个ID的数据
        try {
                  //下行返回的是一个Object对象要强制转化为User
            User user = session.selectOne("selectUserById", id);//注意:selectUserById要与userMapper.xml中的id一样
            System.out.println(user);//打印信息
        }finally {
            session.close();//始终要关掉所以用try-finally
        }

    }
}

5. Create a userMapper.xml file in the resources/Mapper directory

<?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">
<!--
resultType表示查询对象的返回类型为User类型
#{}:从传递过来的参数中取出值
namespace是名称空间,要和User.java所在的cn.mybatis.bean目录对应不能写错
-->
<mapper namespace="cn.mybatis.bean" >
    <select id="selectUserById"  parameterType="java.lang.Integer" resultType="cn.mybatis.bean.User">

            select * from user where id=#{id}
    </select>
</mapper>

Run it and find that the information with id 1 is successfully retrieved

Guess you like

Origin blog.csdn.net/Zhongtongyi/article/details/106090219