Mybatis学习01:Mybatis入门案例及工作原理分析

Mybatis学习01:Mybatis入门案例及工作原理分析

  • 传统JDBC的分析
  • Mybatis的使用
    • 项目准备
    • Mybatis入门案例1-使用xml配置sql语句
    • Mybatis入门案例2-使用注解配置sql语句
    • Mybatis入门案例3-手动编写持久层实现类
    • 入门案例的分析
  • Mybatis工作原理分析

传统JDBC的分析

一个传统的JDBC程序如下:

public static void main(String[] args) {
    
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    
    try {
        //1. 加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2. 获得链接
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database", "username", "password"); 
        //3. 创建statement
        String sql = "select * from user where id = ? and username = ?";
        preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, "王五");
  		// 4. 执行statement
        resultSet = preparedStatement.executeQuery();
        // 5. 遍历结果
        while (resultSet.next()) {
        	System.out.println(resultSet.getString("id") + "" + resultSet.getString("username"));
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 6. 释放资源
        if (resultSet != null) {
            try {resultSet.close(); } catch (SQLException e) {e.printStackTrace(); } 
        }
        if (preparedStatement != null) {
            try {preparedStatement.close(); } catch (SQLException e) {e.printStackTrace(); } 
        }
        if (connection != null) {
            try {connection.close(); } catch (SQLException e) {e.printStackTrace(); } 
        }
    }
}

可以看到,直接使用传统的JDBC,存在以下问题:

  1. 频繁创建数据库连接存在性能问题,可以试用数据库连接池来解决
  2. sql语句在代码中硬编码,改变sql需要改变java代码,可以将sql语句写进配置或注解中
  3. 对结果集合的解析过程复杂且字段硬编码进java代码中了,可以将数据库记录封装成pojo对象

Mybatis的使用

项目准备

  1. 在数据库中创建表users并添加数据

    DROP TABLE IF EXISTS `users`;
    
    CREATE TABLE `users` (
      `id` int(11) NOT NULL auto_increment,
      `username` varchar(32) NOT NULL COMMENT '用户名称',
      `birthday` datetime default NULL COMMENT '生日',
      `sex` char(1) default NULL COMMENT '性别',
      `address` varchar(256) default NULL COMMENT '地址',
      PRIMARY KEY  (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    insert  into `users`(`id`,`username`,`birthday`,`sex`,`address`) values (41,'老王','2018-02-27 17:47:08','男','北京'),(43,'小二王','2018-03-04 11:34:34','女','北京金燕龙'),(45,'传智播客','2018-03-04 12:04:06','男','北京金燕龙'),(46,'老王','2018-03-07 17:37:26','男','北京'),(48,'小马宝莉','2018-03-08 11:44:00','女','北京修正');
    
  2. 创建Maven项目并在pom.xml中引入依赖坐标如下

    <dependencies>
    	<dependency>
    		<groupId>org.mybatisgroupId>
    		<artifactId>mybatisartifactId>
    		<version>3.4.5version>
    	dependency>
        
    	<dependency>
    		<groupId>junitgroupId>
    		<artifactId>junitartifactId>
    		<version>4.10version>
    		<scope>testscope>
    	dependency>
        
    	<dependency>
    		<groupId>mysqlgroupId>
    		<artifactId>mysql-connector-javaartifactId>
    		<version>5.1.6version>
    		<scope>runtimescope>
    	dependency>
        
    	<dependency>
    		<groupId>log4jgroupId>
    		<artifactId>log4jartifactId>
    		<version>1.2.12version>
    	dependency>
    dependencies>
    

    resources目录下创建log4j的配置文件log4j.properties如下:

    # Set root category priority to INFO and its only appender to CONSOLE.
    #log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
    log4j.rootCategory=debug, CONSOLE, LOGFILE
    
    # Set the enterprise logger category to FATAL and its only appender to CONSOLE.
    log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
    
    # CONSOLE is set to be a ConsoleAppender using a PatternLayout.
    log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
    log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
    log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
    
    # LOGFILE is set to be a File appender using a PatternLayout.
    log4j.appender.LOGFILE=org.apache.log4j.FileAppender
    log4j.appender.LOGFILE.File=d:\axis.log
    log4j.appender.LOGFILE.Append=true
    log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
    log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
    
  3. 创建与数据库表对应的pojo类型User,注意入门程序中我们要求pojo类User属性名和数据库表users的字段名严格相同

    package cn.maoritian.domain;
    
    public class User implements Serializable {
    
        // 属性名和数据库表字段名严格相同
    	private Integer id;
    	private String username;
    	private Date birthday;
    	private String sex;
    	private String address;
    
        // 各属性的 set 和 get 方法
    	public Integer getId() {return id; }
    	public void setId(Integer id) {this.id = id; }
    	public String getUsername() {return username; }
    	public void setUsername(String username) {this.username = username; }
    	public Date getBirthday() {return birthday; }
    	public void setBirthday(Date birthday) {this.birthday = birthday; }
    	public String getSex() {return sex; }
    	public void setSex(String sex) {this.sex = sex; }
    	public String getAddress() {return address; }
    	public void setAddress(String address) {this.address = address; }
    
        // toString()方法
    	@Override
    	public String toString() {
    		return "User{" + "id=" + id + ", username='" + username + '\'' + ", birthday=" + birthday + ", sex='" + sex + '\'' + ", address='" + address + '\'' + '}';
    	}
    }
    
  4. 编写持久层接口IUserDao

    package cn.maoritian.dao;
    
    // 持久层接口
    public interface IUserDao {
    
        // 返回所有用户列表
        List<User> findAll();
    }
    

Mybatis入门案例1-使用xml配置sql语句

  1. resource目录下创建Mybatis配置文件SqlMapConfig.xml如下

    
    
    
    
    
    <configuration>
        
    	
    	<environments default="mysql">	
            
            
    		<environment id="mysql">
    			
    			<transactionManager type="JDBC">transactionManager>
    			
    			<dataSource type="POOLED">
    				
    				<property name="driver" value="com.mysql.jdbc.Driver"/>
    				<property name="url" value="jdbc:mysql://localhost:3306/mydatabase"/>
    				<property name="username" value="root"/>
    				<property name="password" value="123456"/>
    			dataSource>
    		environment>
            
    	environments>
        
    configuration>
    
  2. 实现持久层接口

    我们把sql语句写进xml文件中,让Mybatis框架通过反射给我们提供持久层接口的实现类.

    1. 配置持久层接口的sql语句

      我们在resource目录下创建cn/maoritian/dao/IUserDao.xml文件.xml文件的路径和文件名与java代码中的包路径和类名严格相同.

      使用标签配置实现的接口,