当前位置:主页 > 查看内容

从头到尾手把手教你搭建阅读Mybatis源码的环境(程序员必备技能)

发布时间:2021-06-18 00:00| 位朋友查看

简介:文章目录 一、下载Mybatis源码 二、配置Maven 一、简介 maven是什么 二、在Windows下配置Maven环境 三、下载Maven 四、配置Maven环境变量 五、其他注意事项 1、Maven仓库 1、修改Maven的本地仓库 2、修改Maven的中央仓库 六、settings.xml文件全部 过滤掉注……

先放上编译好的mybatis:
https://github.com/truedei/mybatis-notes

自己下载哦,还有注解。

一、下载Mybatis源码

Mybatis的GitHub开源地址:
https://github.com/mybatis/mybatis-3/

进入github官网后打开Releases,可以通过Releases找到最新的或者不同的版本进行下载源码
image.png

直接下载Source code
image.png

这是解压之后的内容:
image.png

下载Mybatis需要一个依赖的项目:
https://github.com/mybatis/parent/releases

image.png

二、配置Maven

一、简介

maven是什么?

二、在Windows下配置Maven环境

Maven 3.3+需要JDK 1.7或更高版本才能执行

想要安装Maven需要下载maven压缩包,无需安装,在windows下只需要配置windows环境变量。

言归正传

开始!

本次教程我所使用的各个版本号(希望能和我一样):

1、JDK 1.8


2、Maven3.5.3 (自己下载最新版一般都没有问题)


3、win10  64位操作系统

JDK环境,Maven环境省略。这里假设你已经会了。

我使用的版本号:

C:\Users\zhenghui>java -version
java version "1.8.0_172-ea"
Java(TM) SE Runtime Environment (build 1.8.0_172-ea-b03)
Java HotSpot(TM) 64-Bit Server VM (build 25.172-b03, mixed mode)

C:\Users\zhenghui>
C:\Users\zhenghui>
C:\Users\zhenghui>mvn -version
Apache Maven 3.5.3 (3383c37e1f9e9b3bc3df5050c29c8aff9f295297; 2018-02-25T03:49:05+08:00)
Maven home: E:\soft\apache-maven-3.5.3\apache-maven-3.5.3\bin\..
Java version: 1.8.0_172-ea, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.8.0_172\jre
Default locale: zh_CN, platform encoding: GBK
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"

C:\Users\zhenghui>

三、下载Maven

Maven的官网:

https://maven.apache.org/

强烈推荐一定要到官网下载,又不花钱对吧,英语不好不要紧,有道随时都在呢

把下载好的压缩文件解压出来

最好放到你自己的安装目录下

E:\soft\apache-maven-3.5.3\apache-maven-3.5.3

四、配置Maven环境变量

右键 “计算机”,选择 “属性”,之后点击 “高级系统设置”,点击"环境变量",来设置环境变量,有以下系统变量需要配置:

1、新建系统变量 MAVEN_HOME,变量值:E:\soft\apache-maven-3.5.3\apache-maven-3.5.3

2、编辑系统变量 Path,添加变量值:%MAVEN_HOME%\bin

测试是否成功

Microsoft Windows [版本 10.0.17134.648]
(c) 2018 Microsoft Corporation。保留所有权利。

C:\Users\zhenghui>mvn -v
Apache Maven 3.5.3 (3383c37e1f9e9b3bc3df5050c29c8aff9f295297; 2018-02-25T03:49:05+08:00)
Maven home: E:\soft\apache-maven-3.5.3\apache-maven-3.5.3\bin\..
Java version: 1.8.0_172-ea, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.8.0_172\jre
Default locale: zh_CN, platform encoding: GBK
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"

C:\Users\zhenghui>

五、其他注意事项

1、Maven仓库

在 Maven 的术语中,仓库是一个位置(place)。

Maven 仓库是项目中依赖的第三方库,这个库所在的位置叫做仓库。

在 Maven 中,任何一个依赖、插件或者项目构建的输出,都可以称之为构件。

Maven 仓库能帮助我们管理构件(主要是JAR),它就是放置所有JAR文件(WAR,ZIP,POM等等)的地方。

Maven 仓库有三种类型:

  • 本地(local)
  • 中央(central)
  • 远程(remote)

详细介绍请点击:http://www.runoob.com/maven/maven-repositories.html

1、修改Maven的本地仓库

为什么修改:

因为本地仓库默认在C盘,所以不建议默认在C盘,以后C盘会越来越大的。

1)、打开settings.xml文件

2)、修改为下图所示的:

2、修改Maven的中央仓库

我使用的是阿里云的:

在上面打开的文件里找到mirrors添加上就行

<mirrors>
    <mirror>
      <id>alimaven</id>
      <name>aliyun maven</name>
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
      <mirrorOf>central</mirrorOf>        
    </mirror>
</mirrors>

六、settings.xml文件全部

过滤掉注释的:

<?xml version="1.0" encoding="UTF-8"?>

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">

<localRepository>E:\soft\apache-maven-3.5.3\local</localRepository>

  <pluginGroups>
   
  </pluginGroups>

  <proxies>
  
  </proxies>

  <servers>
   
  </servers>

  <mirrors>
  
    <mirror>  
      <id>aliyun</id>  
      <name>aliyun</name>  
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
      <mirrorOf>central</mirrorOf> 
    </mirror>  
  </mirrors>

  <profiles>

  </profiles>

</settings>

未过滤注释的:

<?xml version="1.0" encoding="UTF-8"?>

<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single user,
 |                 and is normally provided in ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all Maven
 |                 users on a machine (assuming they're all using the same Maven
 |                 installation). It's normally provided in
 |                 ${maven.conf}/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start at
 | getting the most out of your Maven installation. Where appropriate, the default
 | values (values used when the setting is not specified) are provided.
 |
 |-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  本地仓库配置
  -->
<localRepository>E:\soft\apache-maven-3.5.3\local</localRepository>

  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set to false,
   | maven will use a sensible default value, perhaps based on some other setting, for
   | the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->

  <!-- offline
   | Determines whether maven should attempt to connect to the network when executing a build.
   | This will have an effect on artifact downloads, artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->

  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
   | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
  </pluginGroups>

  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to the network.
   | Unless otherwise specified (by system property or command-line switch), the first proxy
   | specification in this list marked as active will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>

  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used within the system.
   | Authentication profiles can be used whenever maven must make a connection to a remote server.
   |-->
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a particular server, identified by
     | a unique name within the system (referred to by the 'id' attribute below).
     |
     | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are
     |       used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->

    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
  </servers>

  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote repositories.
   |
   | It works like this: a POM may declare a repository to use in resolving certain artifacts.
   | However, this repository may have problems with heavy traffic at times, so people have mirrored
   | it to several places.
   |
   | That repository definition will have a unique id, so we can create a mirror reference for that
   | repository, to be used as an alternate download site. The mirror site will be the preferred
   | server for that repository.
   |-->
  <mirrors>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository. The repository that
     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     -->
    <mirror>  
      <id>aliyun</id>  
      <name>aliyun</name>  
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
      <mirrorOf>central</mirrorOf> 
    </mirror>  
  </mirrors>

  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways, and which can modify
   | the build process. Profiles provided in the settings.xml are intended to provide local machine-
   | specific paths and repository locations which allow the build to work in the local environment.
   |
   | For example, if you have an integration testing plugin - like cactus - that needs to know where
   | your Tomcat instance is installed, you can provide a variable here such that the variable is
   | dereferenced during the build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
   | section of this document (settings.xml) - will be discussed later. Another way essentially
   | relies on the detection of a system property, either matching a particular value for the property,
   | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
   | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
   | Finally, the list of active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
   |       repositories, plugin repositories, and free-form properties to be used as configuration
   |       variables for plugins in the POM.
   |
   |-->
  <profiles>
    <!-- profile
     | Specifies a set of introductions to the build process, to be activated using one or more of the
     | mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>
     | or the command line, profiles have to have an ID that is unique.
     |
     | An encouraged best practice for profile identification is to use a consistent naming convention
     | for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
     | This will make it more intuitive to understand what the set of introduced profiles is attempting
     | to accomplish, particularly when you only have a list of profile id's for debug.
     |
     | This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
    <profile>
      <id>jdk-1.4</id>

      <activation>
        <jdk>1.4</jdk>
      </activation>

      <repositories>
        <repository>
          <id>jdk14</id>
          <name>Repository for JDK 1.4 builds</name>
          <url>http://www.myhost.com/maven/jdk14</url>
          <layout>default</layout>
          <snapshotPolicy>always</snapshotPolicy>
        </repository>
      </repositories>
    </profile>
    -->

    <!--
     | Here is another profile, activated by the system property 'target-env' with a value of 'dev',
     | which provides a specific path to the Tomcat instance. To use this, your plugin configuration
     | might hypothetically look like:
     |
     | ...
     | <plugin>
     |   <groupId>org.myco.myplugins</groupId>
     |   <artifactId>myplugin</artifactId>
     |
     |   <configuration>
     |     <tomcatLocation>${tomcatPath}</tomcatLocation>
     |   </configuration>
     | </plugin>
     | ...
     |
     | NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
     |       anything, you could just leave off the <value/> inside the activation-property.
     |
    <profile>
      <id>env-dev</id>

      <activation>
        <property>
          <name>target-env</name>
          <value>dev</value>
        </property>
      </activation>

      <properties>
        <tomcatPath>/path/to/tomcat/instance</tomcatPath>
      </properties>
    </profile>
    -->
  </profiles>

  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>

祝你学习愉快!

三、IDEA导入Mybatis源码

务必提前配置好maven,可参考上面的内容,也可以参考,我写的这篇文章:
https://blog.csdn.net/qq_17623363/article/details/88858907

打开IDEA后,点击Open or Import
image.png

或者:如果已经打开了其他的项目,可以点击File—>Open
image.png

选择自己解压的位置
image.png

导入之后就别动了哦。

初次导入可能会不能立马显示出来全部的内容,例如我的:
image.png

我们看到下面正在下载相关的maven依赖,所以不用管的。我们现在所做的就是“等待”
image.png

稍等片刻,如果网络没问题的话,一会就下载好:下面这是正常的界面,可以看到1号位置的进度条没了,就可以了。

如果你的maven下载的慢,那么可能需要配置一下maven的阿里云仓库地址或者网易的等等,自行百度即可,或者参考我写的maven环境的配置。

image.png

四、IDEA导入Mybatis依赖的项目

image.png

五、编译项目

(一)先编译Mybatis依赖的项目

image.png

(二)再编译Mybatis源码

1、编译之先关闭代码的检查

image.png

image.png

2、注释掉一个maven-pdf-plugin的依赖

image.png

3、修改依赖的mybatis-parent的pom文件位置

image.png

4、编译

image.png

编译完成之后target目录会有一个jar包:
image.png

就代表编译成功了。

六、使用IDEA创建maven多模块项目并使用Mybatis源码

(一)初始配置

New Project
image.png

输入项目的名字
image.png

这样就创建了一个maven项目
image.png

为了不造成困扰,我们把src目录删除
image.png
image.png

还剩下:
image.png

然后在pom文件添加:

 <packaging>pom</packaging>

image.png

(二)创建一个SpringBoot的Model

image.png

因为我们要创建SpringBoot项目,所以可以选择Spring Initializr:
image.png

image.png

可以先选上Mybaits依赖、web依赖、Mysql驱动依赖:
image.png

Finish
image.png

image.png

创建成功的:
image.png

1、在启动之前创建测试接口

image.png

package com.truedei;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@SpringBootApplication
@RequestMapping("/truedei")
public class TruedeiApplication {

    public static void main(String[] args) {
        SpringApplication.run(TruedeiApplication.class, args);
    }


    @RequestMapping("/test1")
    @ResponseBody
    public String trueDei(){
        return "大家好";
    }
    
}

2、启动测试

如果直接启动的话,会出现:
image.png
原因是我们引入的Mybatis依赖,并没有去配置JDBC驱动,数据库账号等。

解决办法:pom文件暂时注释掉Mybatis的依赖

别忘记刷新哦。
image.png

再次启动:
image.png
出现上图所示的结果,就启动成功啦。

3、访问测试

image.png

(三)导入编译好的Mybatis源码为此项目的一个Module

image.png
选上之前的项目目录即可
image.png

image.png

下面这是成功的界面:
image.png

七、测试编译后的Mybatis是否正常可用

整个目录结构如下:

image.png

(一) 配置项目依赖

此时应该是项目依赖咱们编译后的这个mybatis项目,而不是依赖maven仓库的mybatis

image.png

具体步骤如下:
image.png

选择自己编译后的mybatis项目:
image.png
出现如下图所示的就完事了:
image.png

测试是否依赖成功:
image.png
**image.png

(二)创建Mysql数据表

-- auto-generated definition
create table student
(
    id       int auto_increment comment 'id'
        primary key,
    sno      varchar(20) null comment '学号',
    sname    varchar(10) null comment '学生姓名',
    password varchar(20) null comment '密码',
    perms    varchar(20) null comment '权限'
);

(三)创建Student对象类

public class Student {

    private String id;
    private String sno;
    private String sname;
    private String password;

    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", sno='" + sno + '\'' +
                ", sname='" + sname + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

   //....省略get 和set方法
}

(四)创建StudentMapper接口

public interface StudentMapper {

    Student selectById(String id);

}

(五)创建StudentMapper.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.truedei.test1.StudentMapper">

    <select id="selectById" resultType="com.truedei.test1.Student">
      select * from student where id = #{id}
    </select>

</mapper>

(六)创建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">
            </transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://47.105.166.27:3306/test"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!--        <mapper resource="mapper/StudentMapper.xml" url="" class=""/>-->
        <package name="com.truedei.test1"/>
    </mappers>
</configuration>

(七)创建测试程序

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.Reader;

public class MyTest {

    private static SqlSessionFactory sqlSessionFactory;

    public static void main(String[] args) throws IOException{
        //1、创建SqlSessionFactory
        String resource = "mybatis-config.xml";
//        String resource = "md";
        final Reader reader = Resources.getResourceAsReader(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        reader.close();
        //2、获取sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //3、获取mapper
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);//动态代理代理对象

        //4、执行数据库操作,并处理结果集
        Student goods = mapper.selectById("2");
        System.out.println(goods);
    }
}

(八)测试

如果能正常的读取数据库的数据,说明成功了:
image.png

八、可能遇到的问题总结

1、Cannot enable lazy loading because Javassist is not available

出现这个的原因是javassist的依赖并没有成功的加载。

解决办法:

在你测试的项目中引入即可

        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.24.1-GA</version>
        </dependency>

2、NoClassDefFoundError: ognl/PropertyAccessor

和上面javassist的情况一样,ognl没有加载成功

        <dependency>
            <groupId>ognl</groupId>
            <artifactId>ognl</artifactId>
            <version>3.2.10</version>
        </dependency>

image.png

这次你学废了吗?

这次你学废了吗?
这次你学废了吗?
这次你学废了吗?

关注我,继续学。

;原文链接:https://blog.csdn.net/qq_17623363/article/details/115616395
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文


随机推荐