Mybatis入门(一)环境搭建

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。

 

1、个人感觉还是跟着官方文档走稍微稳妥一些

1.1、准备maven库,Mysql5.7,和IDEA

  准备maven库:

 

<dependencies>
        
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.18version>
        dependency>

        
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.3version>
        dependency>

        
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13version>
            <scope>testscope>
        dependency>

        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.10version>
            <scope>providedscope>
        dependency>
    dependencies>

 

还有资源过滤:


    <build>
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
        resources>
    build>

 

2、开始搭建:

 

先去Mysql里创建一个user表:

Mybatis入门(一)环境搭建_第1张图片

 

查看表里的东西等一下要核对:

Mybatis入门(一)环境搭建_第2张图片

 

 

新建maven项目

Mybatis入门(一)环境搭建_第3张图片

 

 

 

在pom里面导入所需要的库:

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.0modelVersion>

    <groupId>org.examplegroupId>
    <artifactId>MybatisTest02artifactId>
    <version>1.0-SNAPSHOTversion>

    <dependencies>
        
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.18version>
        dependency>

        
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.3version>
        dependency>

        
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13version>
            <scope>testscope>
        dependency>

    dependencies>

    
    <build>
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
        resources>
    build>

project>

 

 

根据官方文档所需要一个xml核心配置文件和一个java核心配置类:

Mybatis入门(一)环境搭建_第4张图片

 

 

 

在resources新建一个xml文件起名为mybatis-config把官方文档的xml配置复制过来:

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?useSSL=true&UseUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
                
                <property name="username" value="root"/>
                
                <property name="password" value="root"/>
            dataSource>
        environment>
    environments>

configuration>

 

再把SqlSessionFactory,封装成一个工具类这样就可以方便调用

 

package com.hdlf.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 Mybatisconfig {

    private static SqlSessionFactory sqlSessionFactory;

    static{
        try {
            //使用Mybatis第一步,获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";//这个文件是可以直接读的。
            InputStream inputStream = Resources.getResourceAsStream(resource);//获取配置文件,就是在resource下的文件
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //既然有了sqlSessionFactory,顾名思义,我们就可以从中获得SqlSession
    //SqlSession完全包含了面向数据库执行SQL命令所需的所有方法
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

 

 

数据库表创建好之后,使用IDEA连接:

Mybatis入门(一)环境搭建_第5张图片

 

 

 

 

Mybatis入门(一)环境搭建_第6张图片

 

 

 

然后在新建一个实体类命名为User,里面的变量名字必须和mysql里创建表里面的键值名一样:

package com.hdlf.pojo;

public class User {
    private int id;
    private String name;
    private String pwe;

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

    public User() {
    }

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

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPwe() {
        return pwe;
    }

    public void setPwe(String pwe) {
        this.pwe = pwe;
    }
}

 

新建一个dao层Mapper接口命名为UserMaper:

 

package com.hdlf.dao;

import com.hdlf.pojo.User;

import java.util.List;

public interface UserMapper {

    List getUser();
}

 

然后再新建一个UserMapper.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">

<mapper namespace="com.hdlf.dao.UserMapper">
    
    <select id="getUser" resultType="com.hdlf.pojo.User">
        SELECT * FROM mybatis.user
    select>
mapper>

 

在Test文件里新建一个测试类:

package com.hdlf.dao;

import com.hdlf.pojo.User;
import com.hdlf.utils.Mybatisconfig;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserMapperTest {
    @Test
    public void test(){

        //第一步,获得sqlsession对象
        SqlSession sqlSession = Mybatisconfig.getSqlSession();
        //执行sql
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List s = mapper.getUser();

        for (User user:s){
            System.out.println(user);
        }
        //关闭sqlSession
        sqlSession.close();
    }
}

目录是这样的:

Mybatis入门(一)环境搭建_第7张图片

 

 

     

运行之后会报错:

 

 

 显示绑定异常

 

原因是没有把UserMapper.xml注解到Mybatis-config.xml文件夹里:

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?useSSL=true&UseUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
                
                <property name="username" value="root"/>
                
                <property name="password" value="root"/>
            dataSource>
        environment>
    environments>
    
    <mappers>
        <mapper resource="com/hdlf/dao/UserMapper.xml"/>
    mappers>
configuration>

 

在运行一下

Mybatis入门(一)环境搭建_第8张图片

 

 

学起来很是复杂不过环境搭建好之后就非常轻松,一定要有耐心哦

你可能感兴趣的:(Mybatis入门(一)环境搭建)