MyBatis学习笔记(一):入门介绍

准备好好学习一下SSM框架,首先从最简单的MyBatis开始。主要参考《Java EE互联网轻量型框架整合开发》和《Spring MVC+MyBatis开发 从入门到项目实战》这两本书。本文也可以认为是这两本书的读书笔记,

MyBatis特点

MyBatis是采用配置文件动态管理SQL语句,并含有输入映射、输出映射机制以及数据库连接池配置的持久层框架。

MyBatis的核心组组件分成以下4个部分:

  • SqlSessionFactoryBuilder(构造器): 它会根据配置或者代码来生成SqlSessionFactory,采用的是分步构建的Builder模式。
  • SqlSessionFactory(工厂接口):依赖它来生成SqlSession。
  • SqlSession(会话): 一个既可以发送SQL执行返回结果,又可以获取Mapper的接口。
  • SQL Mapper(映射器): MyBatis新设计存在的组件,它由一个Java接口和XML文件构成,需要给出对应的的SQL和映射规则。

下面开始搭建项目。

准备环境

准备数据库

打开MySql数据库,创建一个简单的数据表并插入几条数据。

  1. 创建数据库mybatis_demo。
create database `mybatis_demo`;
use `mybatis_demo`;
  1. 创建数据表t_users。
drop table if exists `t_users`;
create table `t_users` (
   `id` INT(11) NOT NULL AUTO_INCREMENT,
   `username` VARCHAR(120) COLLATE utf8_bin DEFAULT NULL,
   `password` VARCHAR(50) COLLATE utf8_bin DEFAULT NULL,
   `gender` VARCHAR(5) COLLATE utf8_bin DEFAULT NULL,
   `email` VARCHAR(100) COLLATE utf8_bin DEFAULT NULL,
   `province` VARCHAR(50) COLLATE utf8_bin DEFAULT NULL,
   `city` VARCHAR(120) COLLATE utf8_bin DEFAULT NULL,
   `birthday` DATE DEFAULT NULL,
   PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
  1. 插入几条数据。
insert into `t_users` (`id`, `username`, `password`, `gender`, `email`, `province`, `city`, `birthday`)
values
(1, '张三','111','男','[email protected]','河北省','衡水市','1990-01-01'),
(2, '李四','222','男','[email protected]','河南省','洛阳市','1992-08-08'),
(3, '王五','333','男','[email protected]','湖南省','长沙市','1978-03-15'),
(4, '赵丽','444','女','[email protected]','湖北省','武汉市','1999-12-01');

一个需要注意的地方是引号和反引号的使用。在插入列的时候必须使用引号,其它地方大部分使用反引号。

搭建工程

使用Eclipse创建一个Maven Web项目。打开pom.xml,添加依赖包。分别是MyBatis依赖包、MySql数据库连接jar包 和日志包。


  4.0.0
  com.wyk
  mybatisDemo
  war
  0.0.1-SNAPSHOT
  mybatisDemo Maven Webapp
  http://maven.apache.org
  
  
    
    3.2.6
    1.2.17
  
  
    
    
        mysql
        mysql-connector-java
        5.1.30
    
    
    
        org.mybatis
        mybatis
        ${mybatis.version}
    
    
        log4j
        log4j
        ${log4j.version}
    
    
      junit
      junit
      3.8.1
      test
    
  
  
    mybatisDemo
  

进行开发

下面编写小项目的代码并添加配置文件。

添加实体类

创建com.wyk.mybatisDemo.pojo包并在其中添加Java实体类User,用来和数据表相对应。

package com.wyk.mybatisDemo.pojo;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {

    private int id;
    private String username;
    private String password;
    private String gender;
    private String email;
    private String province;
    private String city;
    private Date birthday;
    
    public User() {}
    
    public User(int id, String username, String password, String gender,
            String email, String province, String city, Date birthday) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.gender = gender;
        this.email = email;
        this.province = province;
        this.city = city;
        this.birthday = birthday;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }   
}

在该实体中,创建了User的所有属性信息和他们的get、set方法,并且创建了一个无参构造函数和一个有参构造函数。

配置日志

在resources目录下创建文件log4j.properties,为log4j日志输出环境配置参数。

#Global logging configuration
#
log4j.rootLogger=DEBUG, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern==%d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n

配置数据库连接池

在resources下创建文件SqlMapConfig.xml,添加数据库连接相关的配置。




    
        
        
    
    
        
            
            
            
            
                
                
                
                
            
        
    
    
        
    

注意开头的DTD不能写错。

配置SQL映射

前面注意到,SqlMapConfig.xml的mappers标签下已经添加了一个引用,这就是我们要创建的文件。创建com.wyk.mybatisDemo.mapper包并添加xml文件usserMapper.xml。





    

创建数据库交互类

创建包com.wyk.mybatisDemo.datasource,并在其中创建一个可以获取sqlSession的类DataConnection,采用了单例模式。

package com.wyk.mybatisDemo.datasource;

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;

public class DataConnection {

    private final static Class LOCK = DataConnection.class;
    private static String resource = "SqlMapConfig.xml";
    private static SqlSessionFactory sqlSessionFactory = null;
    
    private DataConnection() {}
    
    public static SqlSessionFactory getSqlSessionFactory() {
        //加锁,防止多次实例化
        synchronized(LOCK) {
            if(sqlSessionFactory != null) {
                return sqlSessionFactory;
            }
            
            InputStream inputStream;
            try {
                inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            return sqlSessionFactory;
        }
    }
    
    public static SqlSession openSqlSession() {
        if(sqlSessionFactory == null) {
            getSqlSessionFactory();
        }
        return sqlSessionFactory.openSession();
    }   
}

其中类的构造参数加入了private关键字,使其他代码无法创建它。

进行测试

在com.wyk.mybatisDemo.tests包下添加JUnit测试用例MyBatisTest。

package com.wyk.mybatisDemo.tests;

import java.io.IOException;
import java.text.SimpleDateFormat;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import com.wyk.mybatisDemo.datasource.DataConnection;
import com.wyk.mybatisDemo.pojo.User;

import junit.framework.TestCase;

public class MyBatisTest extends TestCase {
    
    @Test
    public void TestSelect() throws IOException {
        SqlSession sqlSession = DataConnection.openSqlSession();
        //statement的格是当前类名+SQL语句的ID
        User user = sqlSession.selectOne("com.wyk.mybatisDemo.tests.findUserById", 1);
        System.out.println("姓名:" + user.getUsername());
        System.out.println("性别:" + user.getGender());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("生日:" + sdf.format(user.getBirthday()));
        System.out.println("所在地:" + user.getProvince() + user.getCity());
        sqlSession.close();
    }
}

右键该类选择Run As->Run Configuration,在Test中选择要测试的方法,并修改Test Runner为JUint3。


测试配置.png

运行测试用例,查看测试结果。


测试结果.png

补充

补充2个小知识点。

"#{}"和"${}"的区别

"#{}"是占位符,类似传统JDBC里面的"?"; "${"}将传入的数据直接显示生成在sql之中。

"#{}"可以防止SQL注入,原则上是可以使用"#{}"的地方全用"#{}"。

一些地方必须使用"${}":字符需要进行拼接的时候(比如两侧有%);排序使用order byd动态参数;传入数据库对象(例如表名)。

PS:前面写道字符需要进行拼接的时候必须使用"${}"。后面发现其实使用concat函数可以达到同样的效果,特此记录。

下例中的两个SQL效果是一样的:




"selectOne"和"selectList"

这个比较简单,前者返回一条记录,后者返回多条记录。

你可能感兴趣的:(MyBatis学习笔记(一):入门介绍)