先放上编译好的mybatis:
https://github.com/truedei/mybatis-notes
自己下载哦,还有注解。
一、下载Mybatis源码
Mybatis的GitHub开源地址:
https://github.com/mybatis/mybatis-3/
进入github官网后打开Releases,可以通过Releases找到最新的或者不同的版本进行下载源码
直接下载Source code
这是解压之后的内容:
下载Mybatis需要一个依赖的项目:
https://github.com/mybatis/parent/releases
二、配置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的官网:
强烈推荐一定要到官网下载,又不花钱对吧,英语不好不要紧,有道随时都在呢
把下载好的压缩文件解压出来
最好放到你自己的安装目录下
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
或者:如果已经打开了其他的项目,可以点击File—>Open
选择自己解压的位置
导入之后就别动了哦。
初次导入可能会不能立马显示出来全部的内容,例如我的:
我们看到下面正在下载相关的maven依赖,所以不用管的。我们现在所做的就是“等待”
稍等片刻,如果网络没问题的话,一会就下载好:下面这是正常的界面,可以看到1号位置的进度条没了,就可以了。
如果你的maven下载的慢,那么可能需要配置一下maven的阿里云仓库地址或者网易的等等,自行百度即可,或者参考我写的maven环境的配置。
四、IDEA导入Mybatis依赖的项目
五、编译项目
(一)先编译Mybatis依赖的项目
(二)再编译Mybatis源码
1、编译之先关闭代码的检查
2、注释掉一个maven-pdf-plugin的依赖
3、修改依赖的mybatis-parent的pom文件位置
4、编译
编译完成之后target目录会有一个jar包:
就代表编译成功了。
六、使用IDEA创建maven多模块项目并使用Mybatis源码
(一)初始配置
New Project
输入项目的名字
这样就创建了一个maven项目
为了不造成困扰,我们把src目录删除
还剩下:
然后在pom文件添加:
<packaging>pom</packaging>
(二)创建一个SpringBoot的Model
因为我们要创建SpringBoot项目,所以可以选择Spring Initializr:
可以先选上Mybaits依赖、web依赖、Mysql驱动依赖:
Finish
创建成功的:
1、在启动之前创建测试接口
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、启动测试
如果直接启动的话,会出现:
原因是我们引入的Mybatis依赖,并没有去配置JDBC驱动,数据库账号等。
解决办法:pom文件暂时注释掉Mybatis的依赖
别忘记刷新哦。
再次启动:
出现上图所示的结果,就启动成功啦。
3、访问测试
(三)导入编译好的Mybatis源码为此项目的一个Module
选上之前的项目目录即可
下面这是成功的界面:
七、测试编译后的Mybatis是否正常可用
整个目录结构如下:
(一) 配置项目依赖
此时应该是项目依赖咱们编译后的这个mybatis项目,而不是依赖maven仓库的mybatis
具体步骤如下:
选择自己编译后的mybatis项目:
出现如下图所示的就完事了:
测试是否依赖成功:
**
(二)创建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); } }
(八)测试
如果能正常的读取数据库的数据,说明成功了:
八、可能遇到的问题总结
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>
这次你学废了吗?
这次你学废了吗?
这次你学废了吗?
这次你学废了吗?
关注我,继续学。