Mybatis 基础介绍与逆向工程的构建
Mybatis 系列:
Mybatis 基础介绍与逆向工程的构建:https://blog.youkuaiyun.com/qq_34002221/article/details/86662766
Mybatis 源码分析(一)之 Mybatis 的Executor的初始化:https://blog.youkuaiyun.com/qq_34002221/article/details/86684386
Mybatis 源码分析(二)之 Mybatis 操作数据库的流程:https://blog.youkuaiyun.com/qq_34002221/article/details/86729385
Mybatis 源码分析(三)之 Mybatis 的一级缓存和二级缓存 :https://blog.youkuaiyun.com/qq_34002221/article/details/86726720
优秀博客:
http://www.mybatis.org/mybatis-3/zh/index.html
http://www.mybatis.org/generator/index.html
为什么要用Mybatis?
先看下我们传统JDBC连接数据库的弊端:
-
jdbc 底层没有用连接池、操作数据库需要频繁的创建和关联链接。消耗很大的资源
-
写原生的 jdbc 代码在java中,一旦我们要修改sql的话,java需要整体编译,不利于系统维护
-
使用 PreparedStatement 预编译的话对变量进行设置 123 数字,这样的序号不利于维护
-
返回 result 结果集也需要硬编码。
什么是 MyBatis ?
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
这么看一下,是不是感觉mybatis全给解决了。
开始构建Mybatis工程
pom.xml
<?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.0</modelVersion>
<groupId>com.demo</groupId>
<artifactId>mybatis-test</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
<!-- junit测试包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- 日志文件管理包 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
</dependencies>
<!-- 逆向工程插件 -->
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
项目目录结构
mybatis-config.xml
属性名 | 作用 |
---|---|