ORM:对象关系映射,它只是一种规则。
像MyBatis,Hibernate对jdbc进行了封装。
第一章 回顾JDBC开发
1.优点:简单易学,上手快,非常灵活构建SQL(自己写的),效率高。
2.缺点:代码繁琐(各种try..catch..),难以写出高质量的代码(例如:资源的释放,SQL注入安全性等),开发者既要写业务逻辑,又要写对象(连接对象等)的创建和销毁,必须关注底层具体数据库的语法(例如:分页)(MySQL的分页和Oracle的分页语句不同)。
3.适合于超大批量数据的操作,速度快。
开发步骤:
1.加载数据库的驱动Class.forName().
2.通过DriverManager获取数据库的连接.
3.通过Connection获取Statement或PreparedStatement.
4.将SQL语句绑定到Statement或PreparedStatement中去,准备向数据库发送SQL语句.
5.执行完SQL语句之后,返回对象的结果.
ResultSet set = ps.executeQuery(查询)/int i = ps.executeUpdate(增/删/改),返回影响记录数.
6.依次关闭连接对象ResultSet/Statement/Connection.
如果上述操作需要非查询操作的话,还需要事务的支持,简单的写下代码.
connection.setAutoCommit(false);
connection.commit();
connection.rollback();
第二章 回顾hibernate单表开发
1)优点:不用写SQL,完全以面向对象的方式设计和访问,不用管底层具体数据库的语法,(例如:分页)便于理解。
2)缺点:处理复杂业务时,灵活度差, 复杂的HQL难写难理解,例如多表查询的HQL语句
3)适合于中小批量数据的操作,速度慢。
开发步骤:
1.创建Configuration,加载src/hibernate.cfg.xml配置文件,该配置文件中又去加载xx.hbm.xml文件.
2.通过Configuration创建SessionFactory.
3.通过SessionFactory创建Session.
4.通过Session创建Transaction
5.如果做增删改的话一定要事务,如果做查询的话,事务可选.
6.操作Session的常用API,例如:save()/update()/delete()/get().
7.提交事务,出错后事务回滚.
8.关闭Session.
第三章 什么是MyBatis,MyBatis有什么特点
1.基于上述二种支持,我们需要在中间找到一个平衡点,结合它们的优点,摒弃它们的缺点,这就是MyBatis,现今MyBatis被广泛的企业所采用。
2.MyBatis本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。
3.iBatis一词来源于"internet"和"abatis"的组合,是一个基于Java的持久层框架。iBatis提供的持久层框架包括SQL Maps和Data Access Objects(DAO)
4.JDBC/DBUtils/Spring DAO,Hibernate/Spring ORM,MyBatis同属于ORM解决方案之一。
第四章 MyBatis快速入门
准备开发环境
1.创建项目MyBatis_Study,普通的java项目或者是JavaWeb项目均可,如下图所示:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAUsAAACrCAIAAABg5in/AAATwklEQVR4nO2d3W8b2XmH9z8o0KsiV9u7RQt0sRcFAoFLSf425fWuJdEq6rWplZN1aZK25Xi9FZtQWtsy5Gxsq+bI9MbK1hXEsRxp5HVESO043RQosLnIfhRN07RBv7Bpb4sUCwRo0cS9mJkz7/kYcjgkxeHhj3hg0KOZM+cM55nznjOcl889//zz6XR6+Mgp0C6SB4+PpN/sejUAGD5y6jnP8JOgXSQPpkfSX+16NQAYPnLSNfx3XkoAAPTDNXzk3GMAgH7AcAB0BoYDoDPtNPyv7k4JXLtyo+stBKCf6azhsZU8Vdiq2LZtb08XNndzv9Mrtm3vzBd3dadi2xe2bauW2a2Gp4q1tW43uSdq3qHPpeOGK+EaVtiq2PbTp0+pb6nCk3lLXCgeEW9D9rJXtupUL7O0w+xq1vBUsbbm7YsVQgsMSbOGZ5Z27JUtdjS8CojVThW2KnyxmaUdZ+XKgrivCGeSUAG5zEaHLooncqOcasgH0P00gxs1vUKOXui2N1VzejY2dXzCfC7TK/ba0pMIZY7Iht9Z3rRUrz+9bzUsq0XD6aFhRjVleP2DG7n/pHpTwyMU2NQmqWJtzaplCpvOme0fnIVtuaWZpR3hJAg6LaIa7l0cO9yz0cYKjXL+tGaJLXUuZ/UNZ5tMr9h1egLhUIeu81bFdrdKFZ7MW9vT0qfWuJDgz4Ue/2YRDX995vHGhqj3+oZ14o8bly7bG2Yd7wK8s2b7h97pHtcs27a3L+Q/oFdudiG/NvM92g8zeWiHQ22kXb3QhzvO1On0aICQWdqeL26KBRZrrP5eDb3C2dVqZcup5LUZdYuEj3B6hZ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oF0oij5hKqd/DGoCqTB5yj3n1r+c8xNOkTxTMLzviLXhX1K9lIazNIbcEinvUtbwEyeqkqhOlAzvvVRgom5aRRn52TJlUQnRUlX6R1UT3DKFPHAkmRzJLclWgOF9hy6GOwNyku3Uf+OlcKGnuNjnk1M/IOexQkV5hk/GnRGgSV3qGB6UHE7VBHcddaYaxXsY3p9oYnjC86HEwm9iy9is6SZR88bbnOHMgfRc1fY2981Ra8n23tBz1jNHNlzZBHcdGA7qopHhbr9K0o/TzGqmUTZ9FZV9uGBU/ShdSKsotGUgPVf1VCSOCUW59SH7Uqd/lJugyPQIw4GKuBtueq+Ghif4WXGhP2RjWvZffxzuz3JNlEzvx0wMQ5hUE6bHhLSKMizap/fD6W08tgLdV1D6R6EJMByEJHaGs9fk1OmGfXh4aKfdo2jQBLD79IXhYaa+W0G4xdWJXyDrdBOArsTIcAF6P1ygqXKccLqnEx5q0ATQLeJrOACgdWA4ADoDwwHQGRgOgM78P8vceH8AZx+QAAAAAElFTkSuQmCC" alt="" />
2.添加项目所需的两个主要jar包:mybatis-3.2.8.jar和mysql-connector-java-5.0.8-bin.jar,以及有关的日志包.
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQMAAACBCAIAAABLvEj7AAALPklEQVR4nO2dz67jNBTGea7K9N5ISAgkkJg7nbtACMSutGwAIQ1IbdHsAanR3B1spoHRTF8gfQkeiYUTx/+TOGly7H5Xv8VMnKRO6q+2E3/nfMDuMgDAB7PXAAAKQAkAZAxKAIADJQCQMSgBAM5sSvjv3x847C57enr6brM1twMwGSSUwO6y7zbbp6cnczsA00BCCegTwOyQUAJLtE9YrA6nstit7mevCWhlkBL++uvvL56/CDuWVJ+wWG6PZXm5XMoyXy/1husvZXfZYpNfLpfjxjgQSoiHQUo4n8/n8/n3P/786ONP+h5Lp09YLB93RdXE13lZ5tuepWVZ5MeiNJUAImIEJZzP53fv3r385ddex5LqEwSLTV4WhwfbD7+nlOsBSoiacZTA/4p//vn6m287HhvWJy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dv6mc2PLwYnZVns9i19Qv1FKgGAfTPmDkqQz3mxheUT5xQRBtpmzG1KcEQw0Jqdazf9tOIGisgJ3WIUmKpwKcEShKGvEnqGQRikhCEQcfR7pm4JkJKr+9qXTEIJMzr601bCDcYECL7k2ZRwDQIc/akq4QZjAgy85KSUAEAwUAIAGbvL/gewXlkVB0An2QAAAABJRU5ErkJggg==" alt="" />
3.创建MySQL数据库和表.
SQL脚本如下:
创建表的语句不规范!!请自觉忽略。待我补规范语法,这个请自觉忽略
CREATE DATABASE mybatis;
USE mybatis;
CREATE TABLE student(
id INT(5) PRIMARY KEY,
NAME VARCHAR(10),
sal DOUBLE(8,2)
)
执行此脚本,完成数据库和表的创建工作。
4.创建与数据库表对应的实体。
package com.winner.entity; /**
* Created by winner_0715 on 2016/3/23.
* student表对应的实体类
*/
public class Student { private Integer id;//最好使用包装类型
private String name;
private Double sal;//最好使用包装类型
//无参构造方法必须有
public Student() {
} public Student(Integer id, String name, Double sal) {
this.id = id;
this.name = name;
this.sal = sal;
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Double getSal() {
return sal;
} public void setSal(Double sal) {
this.sal = sal;
}
}
5.在entity目录下创建StudentMapper.xml配置文件,表示表和实体的映射关系,
(位置不一定非得放在实体目录中,命名建议是"实体类名+Mapper.xml"),
相当于Hibernate中的xxx.hbm.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,
namespace的值习惯上设置成包名+映射文件名,这样就能够保证namespace的值是唯一的.
这里取映射文件的全限定名,不要.xml后缀名。
mapper标签,所以这个唯一的标识也起名为xxxxMapper,纯属为了记忆!
-->
<mapper namespace="com.winner.entity.StudentMapper">
<!--
resultMap标签:映射实体与表
type属性:表示实体全路径名
id属性:为实体与表的映射取一个任意的唯一的名字
Map标签,所以这个唯一的标识也起名为xxxMap,同样是为了记忆!
-->
<resultMap id="studentMap" type="com.winner.entity.Student">
<!--
id标签:映射主键属性
result标签:映射非主键属性
property属性:实体的属性名
column属性:表的字段名
-->
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sal" column="sal"/>
</resultMap>
<!--
insert标签:要书写一个insert的ql语句
id属性:为insert这个sql操作取唯一的名字,可以取Dao中的对应方法名.
parameterType:要执行的dao中的方法的参数,如果是类的话,必须使用全路径类
-->
<insert id="add1">
<![CDATA[
INSERT INTO student(id,name,sal) VALUES (1,"zhangsan",2000);
]]>
</insert> <insert id="add2" parameterType="com.winner.entity.Student">
<![CDATA[
INSERT INTO student(id,name,sal) VALUES (#{id},#{name},#{sal});
]]>
</insert>
<!--
这里还可以有其他的sql语句
-->
</mapper>
6.在src目录下添加Mybatis的配置文件mybatis-config.xml,
相当于Hibernate中的hibernate.cfg.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> <!-- 加载类路径下的属性文件 -->
<properties resource="db.properties"/> <!-- 设置一个默认的连接环境信息 -->
<environments default="mysql_developer">
<environment id="mysql_developer">
<!-- mybatis使用jdbc事务管理方式 -->
<transactionManager type="JDBC"></transactionManager>
<!-- mybatis使用连接池方式来获取连接 -->
<dataSource type="POOLED">
<!-- 配置与数据库交互的4个必要属性 -->
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
<!-- 连接环境信息,取一个任意唯一的名字 -->
<environment id="oracle_developer">
<!-- mybatis使用jdbc事务管理方式 -->
<transactionManager type="jdbc"/>
<!-- mybatis使用连接池方式来获取连接 -->
<dataSource type="pooled">
<!-- 配置与数据库交互的4个必要属性 -->
<property name="driver" value="${oracle.driver}"/>
<property name="url" value="${oracle.url}"/>
<property name="username" value="${oracle.username}"/>
<property name="password" value="${oracle.password}"/>
</dataSource>
</environment>
</environments> <!-- 加载映射文件-->
<mappers>
<mapper resource="com/winner/entity/StudentMapper.xml"/>
</mappers> </configuration>
db.properties
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://127.0.0.1:3306/mybatis
mysql.username=root
mysql.password=root oracle.driver=oracle.jdbc.driver.OracleDriver
oracle.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
oracle.username=scott
oracle.password=tiger
7.在util目录下创建MyBatisUtil.java工具类
/**
* Created by winner_0715 on 2016/3/23.
* 工具类
*/
public class MybatisUtil {
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
private static SqlSessionFactory sqlSessionFactory;
/**
* 这个工具类加载时加载mybatis.xml配置文件,注意路径。希望类加载的时候就加载配置文件
*/
static{
try {
Reader reader = Resources.getResourceAsReader("mybatis.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 禁止外界通过new方法创建
*/
private MybatisUtil(){}
/**
* 获取SqlSession
*/
public static SqlSession getSqlSession(){
//从当前线程中获取SqlSession对象
SqlSession sqlSession = threadLocal.get();
//如果SqlSession对象为空
if(sqlSession == null){
//在SqlSessionFactory非空的情况下,获取SqlSession对象
sqlSession = sqlSessionFactory.openSession();
//将SqlSession对象与当前线程绑定在一起
threadLocal.set(sqlSession);
}
//返回SqlSession对象
return sqlSession;
}
/**
* 关闭SqlSession与当前线程分开
*/
public static void closeSqlSession(){
//从当前线程中获取SqlSession对象
SqlSession sqlSession = threadLocal.get();
//如果SqlSession对象非空
if(sqlSession != null){
//关闭SqlSession对象
sqlSession.close();
//分开当前线程与SqlSession对象的关系,目的是让GC尽早回收
threadLocal.remove();
}
} /**
* 测试
*/
public static void main(String[] args) {
Connection conn = MybatisUtil.getSqlSession().getConnection();
System.out.println(conn!=null?"连接成功":"连接失败");
} }
8.在DAO目录下创建StudentDao.java类,这里就不使用接口了,实际项目中必须使用接口.
就像在Hibernate中使用的那样,DAO调用mybatis提供的有关方法完成对数据库的操作。
public class StudentDao { public void add1() throws Exception{
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtil.getSqlSession();
//事务开始(默认)
//读取StudentMapper.xml映射文件中的SQL语句
int i = sqlSession.insert("com.winner.entity.StudentMapper.add1");
System.out.println("本次操作影响了"+i+"行");
//事务提交
sqlSession.commit();
}catch(Exception e){
e.printStackTrace();
//事务回滚
sqlSession.rollback();
throw e;
}finally{
MybatisUtil.closeSqlSession();
}
} public void add2(Student student) throws Exception{
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtil.getSqlSession();
//事务开始(默认)
//读取StudentMapper.xml映射文件中的SQL语句
sqlSession.insert("com.winner.entity.StudentMapper.add2",student);
//事务提交
sqlSession.commit();
}catch(Exception e){
e.printStackTrace();
//事务回滚
sqlSession.rollback();
throw e;
}finally{
MybatisUtil.closeSqlSession();
}
} public static void main(String[] args) throws Exception{
StudentDao dao = new StudentDao();
//dao.add1();
dao.add2(new Student(2,"lisi",3000d));
}
}
想看log4j日志信息的话需要log4j的jar包,然后把log4j.properties放在src下
log4j.rootLogger=debug,stdout,logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
mybatis工作流程
1.通过Reader对象读取src目录下的mybatis.xml配置文件(该文本的位置和名字可任意)
2.通过SqlSessionFactoryBuilder对象创建SqlSessionFactory对象
3.从当前线程中获取SqlSession对象
4.事务开始,在mybatis中默认
5.通过SqlSession对象读取StudentMapper.xml映射文件中的操作编号,从而读取sql语句
6.事务提交,必写
7.关闭SqlSession对象,并且分开当前线程与SqlSession对象,让GC尽早回收