MyBatis入门配置

目录

一、创建数据库

 二、创建mybatis核心配置文件

三、配置pom.xml

四、创建pojo

五、创建工具类获取SqlSession对象

六、创建Dao层接口

七、创建Dao层所对应的xml文件

八、编写测试类进行测试


 

一、创建数据库

CREATE DATABASE `mybatis_db`

USE `mybatis_db`

CREATE TABLE `user`(
	`id` int(20),
	`name` VARCHAR(30),
	`pwd` VARCHAR(30),
	PRIMARY KEY(`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO `user` VALUES
(1, 'hongyyds', '123123'),
(2, 'shiyu', '110000'),
(3, 'feiyu', '666321')

 二、创建mybatis核心配置文件

        2.1、在maven的资源目录(resource)中创建mybatis核心配置文件

<?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">
        <!--id 标识-->
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--mysql驱动程序-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--数据库URL地址-->
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_db?useSSl=true&useUnicode=true&characterEncoding=utf-8"/>
                <!--mysql账号-->
                <property name="username" value="root"/>
                <!--mysql密码-->
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!--每一个xml配置文件都需要在mybatis的核心配置文件中注册才能生效-->
    <mappers>
        <mapper resource="cong/hong/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

三、配置pom.xml

        3.1、配置插件junit、mysql和mybatis

<dependencies>
        <!-- mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <!-- mybatis驱动 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

        3.2、配置文件目录过滤(解决maven项目文件不输出的情况)

<!--解决maven项目文件不输出的情况-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>

            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
    </build>
MyBatis入门配置

四、创建pojo

package cong.hong.pojo;

import java.io.Serializable;

public class User implements Serializable {
    private String id;
    private String name;
    private String pwd;

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

    public User() {
    }

    public User(String id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
}

五、创建工具类获取SqlSession对象

package cong.hong.utils;

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.IOException;
import java.io.InputStream;

public class MybatisUtils {
    private static InputStream inputStream;
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //mybatis核心配置文件路径
            String resource = "config.xml";
            //读取配置文件
            inputStream = Resources.getResourceAsStream(resource);
            //构建SqlSessionFactory类对象
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @return SqlSession对象
     */
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

六、创建Dao层接口

package cong.hong.mapper;

import cong.hong.pojo.User;

import java.util.List;

public interface UserMapper {
    //或如用戶列表
    public List<User> getUserList();
}

七、创建Dao层所对应的xml文件

        7.1、创建xml文件实现查询功能

<?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">
<!-- namespace 绑定的工作区 Java文件-->
<mapper namespace="cong.hong.mapper.UserMapper">
    <!--select:查询, id:接口中的要实现的方法名, resultType:返回值的类型(泛型中的类型) -->
    <select id="getUserList" resultType="cong.hong.pojo.User">
        select * from mybatis_db.user
    </select>
</mapper>

7.2、在MyBatis核心配置文件中注册xml文件

        注:每一个Dao层接口对象对应的xml文件都需要在MyBatis的核心配置文件中进行才能生效!!

<?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">
        <!--id 标识-->
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--mysql驱动程序-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--数据库URL地址-->
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_db?useSSl=true&useUnicode=true&characterEncoding=utf-8"/>
                <!--mysql账号-->
                <property name="username" value="root"/>
                <!--mysql密码-->
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!--注意:每一个xml配置文件都需要在mybatis的核心配置文件中注册才能生效-->
    <mappers>
        <mapper resource="cong/hong/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

八、编写测试类进行测试

        8.1、测试代码:

package cong.hong.mapper;

import cong.hong.pojo.User;
import cong.hong.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

public class UserMapperTest {
    @Test
    public void test(){
        SqlSession session = new MybatisUtils().getSqlSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        for (User user : mapper.getUserList()) {
            System.out.println(user);
        }

        if(session!=null){
            session.close();
        }
    }

}

         8.2、运行结果

MyBatis入门配置

 

 

 

 

 

 

 

 


上一篇:Machine Learning A-Z学习笔记


下一篇:Spring调用对应参数构造器创建对象