2019独角兽企业重金招聘Python工程师标准>>>
ORM:Object Relation Mapping:对象关系映射,通俗理解就是将一个对象相关属性和数据库数据进行关联(映射),传统我们对数据库数据的操作可以通过ORM框架转移到对对象的操作上来,这无疑有利于提高程序的开发效率和项目的可维护性,本质是对传统的JDBC操作高级封装
工作流程
mybatis通过sqlSessionFactory创建sqlSession, sqlSession表示应用程序与数据库的会话,当用户使用mapper.xml文件中配置的的方法时,mybatis首先会解析sql动态标签为对应数据库sql的形式,并将其封装进MapperStatement对象,然后通过executor将sql注入数据库执行,并返回结果
常见ORM框架:hibernate、mybatis
mybatis主要通过两个配置文件(sqlMapConfig.xml和Mapper.xml),来配置数据库和对象的关系
sqlMapConfig.xml
Mybatis全局配置文件,主要配置mybatis的环境参数、映射对象运行参数。
mybatis的环境参数:数据源配置、事务控制
映射对象运行参数:映射对象的别名设置、映射对象配置文件加载
案例:
mapper.xml:主要配置映射对象在数据库中相关的操作
案例:
delete from user where id=#{id}
update user set name=#{name},passwd=#{passwd} where id=#{id}
insert into user(id,name,passwd) values(#{id},#{name},#{passwd})
mapper.xml对应的对象:
package com.zhiwei.domain;
public class User {
private int id;
private String name;
private String passwd;
public User(){}
public User(int id, String name, String passwd) {
super();
this.id = id;
this.name = name;
this.passwd = passwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", passwd=" + passwd + "]";
}
}
sqlSession工具类:
package com.zhiwei.tool;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
* Mybatis工具类
* @author Yang Zhiwei
*/
public final class MybatisTool {
private static InputStream is=null;
private static SqlSession sqlSession=null;
/**
* 获取Mybstis SqlSession会话
* @return
*/
public static SqlSession getSession(){
try {
is=Resources.getResourceAsStream("SqlMapConfig.xml");
} catch (IOException e) {
e.printStackTrace();
}
/**本质通过调用DefaultSqlSessionFactory创建sqlSession
*DefaultSqlSession:与数据库进行JDBC操作的类
* MappedStatement:与JDBC操作的StateMent类类似,封装sql信息,
* mybatis的动态sql标签在提交给数据库之前会进行sql的规范化,控制台日志显示
* executor:真正和数据库进行交互的执行者
* configuration:mybatis配置文件信息的封装类
*部分源码:
* @Override
public int update(String statement, Object parameter) {
try {
dirty = true;
MappedStatement ms = configuration.getMappedStatement(statement);
return executor.update(ms, wrapCollection(parameter));
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error updating database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
*
* */
//通过mybatis的控制文件创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
sqlSession=sqlSessionFactory.openSession();
return sqlSession;
}
/**
* 关闭mybatis SqlSession会话
*/
public static void resourceClosing(){
try{
if(sqlSession!=null){
sqlSession.close();
}
if(is!=null){
is.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
对象的操作方法接口(方法名必须与Mapper.xml文件中sql的Id对应,mybatis无法正确解析):
package com.zhiwei.service;
import org.apache.ibatis.session.SqlSession;
import com.zhiwei.domain.User;
import com.zhiwei.tool.MybatisTool;
/***
* 基础服务类
* @author Yang Zhiwei
*/
public class BasicServiceImp{
private static SqlSession sqlSession=null;
//SqlSession初始化
static{
sqlSession=MybatisTool.getSession();
}
/**
* 通过Id查询用户信息
* test:表示命名空间
* findUserById:mapper.xml文件的动态sql id
* test.findUserById:指明访问动态sql地址--->对应:
* @param id
* @return
*/
public static User findUserById(int id) {
return sqlSession.selectOne("test.findUserById", id);
}
/**
* 更新用户信息
* @param user
*/
public static void updateUser(User user) {
sqlSession.update("test.updateUser",user);
sqlSession.commit();
MybatisTool.resourceClosing();
}
/**
* 删除用户信息
* @param id
*/
public static void deleteUserById(int id) {
sqlSession.delete("test.deleteUserById", id);
sqlSession.commit();
MybatisTool.resourceClosing();
}
/**
* 添加用户信息
* @param user
*/
public static void addUser(User user) {
sqlSession.insert("test.addUser",user);
sqlSession.commit();
MybatisTool.resourceClosing();
}
}
测试类:
package com.zhiwei.test;
import com.zhiwei.domain.User;
import com.zhiwei.service.BasicServiceImp;
public class BasicTest {
public static void main(String[] args) {
User user=BasicServiceImp.findUserById(1);
System.out.println(user);
}
}
结果:
DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG [main] - Class not found: org.jboss.vfs.VFS
DEBUG [main] - JBoss 6 VFS API is not available in this environment.
DEBUG [main] - Class not found: org.jboss.vfs.VirtualFile
DEBUG [main] - VFS implementation org.apache.ibatis.io.JBoss6VFS is not valid in this environment.
DEBUG [main] - Using VFS adapter org.apache.ibatis.io.DefaultVFS
DEBUG [main] - Find JAR URL: file:/D:/BaiduYunDownload/mybatis/bin/com/zhiwei/domain
DEBUG [main] - Not a JAR: file:/D:/BaiduYunDownload/mybatis/bin/com/zhiwei/domain
DEBUG [main] - Reader entry: User.class
DEBUG [main] - Reader entry: UserMapper.xml
DEBUG [main] - Listing file:/D:/BaiduYunDownload/mybatis/bin/com/zhiwei/domain
DEBUG [main] - Find JAR URL: file:/D:/BaiduYunDownload/mybatis/bin/com/zhiwei/domain/User.class
DEBUG [main] - Not a JAR: file:/D:/BaiduYunDownload/mybatis/bin/com/zhiwei/domain/User.class
DEBUG [main] - Find JAR URL: file:/D:/BaiduYunDownload/mybatis/bin/com/zhiwei/domain/UserMapper.xml
DEBUG [main] - Not a JAR: file:/D:/BaiduYunDownload/mybatis/bin/com/zhiwei/domain/UserMapper.xml
DEBUG [main] - Reader entry:
DEBUG [main] - Checking to see if class com.zhiwei.domain.User matches criteria [is assignable to Object]
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Openning JDBC Connection
DEBUG [main] - Created connection 1211076369.
DEBUG [main] - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@482f8f11]
DEBUG [main] - ==> Preparing: select *from user where id=?
DEBUG [main] - ==> Parameters: 1(Integer)
User [id=1, name=zhangsan, passwd=zhangsan]
日志分析:从Log4J的控制台日志可以清楚看到,mybatis的本质就是JDBC操作, 对数据库数据的操作就可以直接通过像调用普通方法一样进行,非常方便
数据库数据: