定义:
写作时间:2015年8月27日11:15:50
mybatis是一个java持久层框架,java中操作关系型 数据库用的是jdbc,mybatis是对jdbc的一个封装。本次从基础讲mybatis的前面回顾,从理论结合实例讲解。本文目前是最新的基于maven的mybatis的教程,是自己学习回顾。
1、 开发环境
jdk1.7.0_79
idea:intellij_14.1.4
mysql:mysql5.6
2、为什么有Mybatis-jdbc编程中问题
据库用的是jdbc,mybatis是对jdbc的一个封装。本次从基础讲mybatis的前面回顾,从理论结合实例讲解。我们先看看jdbc
import java.sql.*;
/**
* Created by Administrator on 2015/8/27 0027.
*/
public class JdbcTest {
public static void main(String[] args) {
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
try {
//隐射驱动
Class.forName("com.mysql.jdbc.Driver");
connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/shiro?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull", "root","123456");
String sql="SELECT * FROM user where username=?";
preparedStatement=connection.prepareStatement(sql);
System.out.println(preparedStatement);
preparedStatement.setString(1,"王五");
resultSet=preparedStatement.executeQuery();
while(resultSet.next()){
System.out.println(resultSet.getString("username")); ;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(resultSet!=null){
resultSet.close();
}
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}1、jdbc需要频繁链接
解决方案设想:建立数据连接池
2、sql语句是硬编码
解决方案设想:将sql统一配置
3、preparedStatement占位符硬编码
解决方案设想:sql占位符配置在文件中
4、遍历结果集硬编码
解决方案设想:java对象遍历
3、mybatis架构(重点)
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis,实质上Mybatis对ibatis进行一些改进。 目前mybatis在github上托管。
MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码。

4、mybatis入门程序(Jar)
4.1导入jar包mybatis在github上托管,可以去上面下载jar包(地址:https://github.com/mybatis/mybatis-3/releases),由于但是用的maven就直接贴出来配置。
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>Mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<!--mybatis包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<!--log4j官方推荐jar-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.3</version>
</dependency>
</dependencies>以上jar包,关于log4j,我会另外讲一下,请参考log4j专题
由于篇幅关系,下一章进入入门程序
如有疑问:qq群:78275755(目前木有人,来啦更好)
本项目1-5章 初级教程 项目百度分享盘:
本项目1-5章 初级教程 项目百度分享盘:
http://pan.baidu.com/s/1o63SUaI