本课程视频教程地址为:http://edu.51cto.com/course/14674.html

1、为什么要学习MyBatis

1.1、传统jdbc回顾

package cn.org.kingdom.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Test;
public class TestJdbc {
    @Test
    public void test() throws ClassNotFoundException, SQLException {
        //加载驱动
        Class.forName("org.gjt.mm.mysql.Driver");
        //获取连接
        String url = "jdbc:mysql://localhost:3306/mytest?useUnicode=true&characterEncoding=utf8";
        String username = "root";
        String pwd = "root";
        Connection conn = DriverManager.getConnection(url, username, pwd);
        //执行sql
        String sql = "select * from user where userid = ?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        //结果迭代
        while(rs.next()) {
            System.out.println(rs.getInt("userid"));
            System.out.println(rs.getString("username"));
        }
        //释放资源
        rs.close();
        pstmt.close();
        conn.close();
    }
}

1.2、传统JDBC代码存在的问题

1.数据库连接频繁的创建和关闭,缺点浪费数据库的资源,影响操作效率

解决方式:采用了连接池机制来解决

2.sql语句是硬编码,如果需求变更需要修改sql,就需要修改java代码,需要重新编译,系统不易维护。

解决方式:将sql语句统一配置在文件中,修改sql不需要修改java代码

3.通过preparedStatement向占位符设置参数,存在硬编码( 参数位置,参数)问题。系统不易维护

解决方式:将sql中的占位符及对应的参数类型配置在配置文件中,能够自动输入映射

4.遍历查询结果集存在硬编码(列名)

自动进行sql查询结果向java对象的映射(输出映射)

2、MyBatis

2.1、Mybatis简介

MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis,实质上Mybatis对ibatis进行一些改进。 目前mybatis在github上托管。git(分布式版本控制,当前比较流程)

MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码。

Mybatis通过xml或注解的方式将要执行的各种statement(statement、preparedStatemnt、CallableStatement)配置起来,并通过java对象和statement中的sql进行映射生成最终执行的sql语句,最后由mybatis框架执行sql并将结果映射成java对象并返回。

2.2、MyBatis架构

3、MyBatis快速入门

3.1、建表

CREATE TABLE tb_user (
       userid number(4) NOT NULL primary key,
       user_name varchar2(100),
       pwd  varchar2(100),
       age number(3) ,
       sex varchar(2), 
       birthday date 
);
create sequence seq_user;
--插入测试数据
insert into tb_user(userid,user_name,pwd,age,sex,birthday)
values(seq_user.nextval,'张三','123456',10,'男',sysdate);

insert into tb_user(userid,user_name,pwd,age,sex,birthday)
values(seq_user.nextval,'李四','123456',10,'男',sysdate);

insert into tb_user(userid,user_name,pwd,age,sex,birthday)
values(seq_user.nextval,'王五','123456',10,'男',sysdate);

insert into tb_user(userid,user_name,pwd,age,sex,birthday)
values(seq_user.nextval,'赵六','123456',10,'男',sysdate);

select * from tb_user;

3.2、添加jar包

1、mybatis-3.2.3.jar(MyBatis的核心jar包)

2、mysql-connector-java-5.0.4-bin.jar(mysql的jar包)或者 classes12.jar(Oracle的jar包)

3、log4j-1.2.17.jar、slf4j-api-1.7.5.jar、slf4j-log4j12-1.7.5.jar(日志包)

3.3、全局配置文件

在src目录建立一个xml文件,一般情况下命令为:mybatis-config.xml文件




  
    
      
      
        
        
        
        
      
    
  

3.4、添加日志的配置文件

src下目录下建立log4j.properties 文件

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.File=jbit.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout\t
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

3.5、测试连接

package cn.org.kingdom.test;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
public class MyBatisTest {
    @Test
    public void test() throws IOException{
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        System.out.println("sqlSessionFactory:"+sqlSessionFactory);
        SqlSession sqlsession = sqlSessionFactory.openSession();
        System.out.println("sqlsession:"+sqlsession);
        Connection conn = sqlsession.getConnection();
        System.out.println("conn:"+conn);
    }
}

3.6、运行结果

DEBUG - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
sqlSessionFactory:org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@42bf7a35
sqlsession:org.apache.ibatis.session.defaults.DefaultSqlSession@73bb9f3f
DEBUG - Opening JDBC Connection
DEBUG - Created connection 404536294.
DEBUG - Setting autocommit to false on JDBC Connection [oracle.jdbc.driver.T4CConnection@181cbbe6]
conn:oracle.jdbc.driver.T4CConnection@181cbbe6

3.7、创建一个实体类(User)

package cn.org.kingdom.entity;
import java.io.Serializable;
import java.sql.Date;
public class User implements Serializable {
    private int userid;
    private String userName;
    private String pwd;
    private int age;
    private String sex;
    private Date birthday;
    public User() {
        super();
    }

    public User(String userName, String pwd, int age, String sex, Date birthday) {
        super();
        this.userName = userName;
        this.pwd = pwd;
        this.age = age;
        this.sex = sex;
        this.birthday = birthday;
    }

    public User(int userid, String userName, String pwd, int age, String sex,
            Date birthday) {
        super();
        this.userid = userid;
        this.userName = userName;
        this.pwd = pwd;
        this.age = age;
        this.sex = sex;
        this.birthday = birthday;
    }

    public int getUserid() {
        return userid;
    }
    public void setUserid(int userid) {
        this.userid = userid;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    @Override
    public String toString() {
        return "User [userid=" + userid + ", userName=" + userName + ", pwd="
                + pwd + ", age=" + age + ", sex=" + sex + ", birthday="
                + birthday + "]";
    }
}

3.8、创建Mapper映射文件

在src目录下建立UserMapper.xml文件




  

此时还需要将此文件关联到全局配置文件之中



  
    
      
      
        
        
        
        
      
    
  
  
        
  

3.9、编写测试文件

    @Test
    public void testHello() throws IOException{
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        System.out.println("sqlSessionFactory:"+sqlSessionFactory);
        SqlSession sqlsession = sqlSessionFactory.openSession();
        User user = sqlsession.selectOne(User.class.getName()+".findUserById",1);
        System.out.println(user);
    }

3.10、运行结果

DEBUG - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
sqlSessionFactory:org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@42bf7a35
DEBUG - Opening JDBC Connection
DEBUG - Created connection 1476491893.
DEBUG - Setting autocommit to false on JDBC Connection [oracle.jdbc.driver.T4CConnection@58017a75]
DEBUG - ooo Using Connection [oracle.jdbc.driver.T4CConnection@58017a75]
DEBUG - ==>  Preparing: select * from tb_user where userid = ? 
DEBUG - ==> Parameters: 1(Integer)
DEBUG - <==      Total: 1
User [userid=1, userName=null, pwd=123456, age=10, sex=男, birthday=2018-08-07]

此时我们发现,userName字段的值并没有查询出来,出现这个问题的原因主要在于我们的数据库字段和实体类的映射不一致造成的,这里我先给出一种解决方式,修改UserMappper.xml文件




  

重新测试,运行ok

3.11、MyBatis入门总结

1.创建配置文件:mybatis-config.xml,mapper.xml,log4j.properties

2.构建SqlSessionFactory对象

3.创建SqlSession对象

4.通过sqlsession去执行数据库操作

5.提交事务

6.关闭sqlsession