简介:
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。 ——百度百科
创建maven工程:
项目结构:
pom.xml文件:
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 3 <modelVersion>4.0.0</modelVersion> 4 5 <groupId>com.itdoc.mybatis</groupId> 6 <artifactId>mybatis-01</artifactId> 7 <version>1.0-SNAPSHOT</version> 8 <packaging>jar</packaging> 9 10 <name>mybatis-01</name> 11 <url>http://maven.apache.org</url> 12 13 <properties> 14 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 15 </properties> 16 17 <dependencies> 18 <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core --> 19 <dependency> 20 <groupId>org.apache.logging.log4j</groupId> 21 <artifactId>log4j-core</artifactId> 22 <version>2.8.2</version> 23 </dependency> 24 25 <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> 26 <dependency> 27 <groupId>org.mybatis</groupId> 28 <artifactId>mybatis</artifactId> 29 <version>3.4.1</version> 30 </dependency> 31 32 <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> 33 <dependency> 34 <groupId>mysql</groupId> 35 <artifactId>mysql-connector-java</artifactId> 36 <version>5.1.38</version> 37 </dependency> 38 39 <!-- https://mvnrepository.com/artifact/junit/junit --> 40 <dependency> 41 <groupId>junit</groupId> 42 <artifactId>junit</artifactId> 43 <version>4.12</version> 44 </dependency> 45 46 </dependencies> 47 </project>
全局配置文件(mybatis-config.xml):此配置文件不是必须的。
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 <environments default="development"> 7 <environment id="development"> 8 <transactionManager type="JDBC" /> 9 <dataSource type="POOLED"> 10 <property name="driver" value="com.mysql.jdbc.Driver" /> 11 <property name="url" value="jdbc:mysql://localhost:3306/mybatis" /> 12 <property name="username" value="root" /> 13 <property name="password" value="root" /> 14 </dataSource> 15 </environment> 16 </environments> 17 <!-- 将写好的sql映射文件(EmployeeMapper.xml)一定要注册到全局配置文件(mybatis-config.xml)中 --> 18 <mappers> 19 <mapper resource="mapper/EmployeeMapper.xml" /> 20 </mappers> 21 </configuration>
Mybatis中配置中相应的对应关系:
github源码:https://github.com/wcd19901010/Mybatis/tree/master/mybatis-01