1 DAO层框架

  • 框架:是一种整体的解决方案。

1.1 JDBC的步骤

1.2 Hibernate执行的步骤

1.3 MyBaits

2 Mybatis简介

  • Mybatis是支持定制化SQL、存储过程以及高级映射的优秀的持久层框架。
  • Mybatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。
  • Mybatis可以使用简单的XML或者注解用于配置和原始映射,将接口和Java的POJO映射成数据库中的记录。

3 为什么需要Mybatis?

  • Mybatis是一个半自动的持久层框架。
  • JDBC
    • SQL夹在Java代码中,耦合度高导致硬编码内伤。
    • 维护不易且实际开发需求中SQL是有变化的,频繁修改的情况多见。
  • Hibernate和JPA
    • 长难复杂的SQL,对于Hibernate而言处理并不容易。
    • 内部自动生成的SQL,不容易做优化处理。
    • 基于全映射的全自动框架,大量字段的POJO进行部分映射的时候比较困难,导致数据库性能下降。    
  • 对于开发人员而言,核心SQL还是需要自己优化的。
  • SQL和Java代码分开,功能边界清晰,一个专注业务,一个专注数据。

4 下载Mybatis

5 Mybatis之HelloWorld

5.1 编写SQL脚本

DROP DATABASE mybatis;
CREATE DATABASE mybatis;
USE mybatis;
DROP TABLE employee;
CREATE TABLE employee(
    id INT PRIMARY KEY AUTO_INCREMENT,
    last_name ),
    gender ),
    email )
);
INSERT INTO employee (last_name,gender,email) VALUES ('许威威','男','1975356467@qq.com');

5.2 创建javabean

  • Employee.java
package com.xuweiwei.mybatis.pojo;

public class Employee {
    private Integer id;
    private String lastName;
    private String gender;
    private String email;

    public Integer getId() {
        return id;
    }

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

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    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;
    }
}

5.3 在src下加入log4j.properties文件

og4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=debug, stdout 

5.4 在src下新建mybatis-config.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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>

    </mappers>
</configuration>

5.5 新建EmployeeMapper.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="com.xuweiwei.mybatis.pojo.Employee">
    <select id="selectEmployeeById" resultType="com.xuweiwei.mybatis.pojo.Employee">
        select id,last_name lastName,gender,email  from employee where id = #{id}
    </select>
</mapper>

5.6 将EmployeeMapper.xml文件加入到mybatis-config.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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/xuweiwei/mybatis/mapper/EmployeeMapper.xml"/>
    </mappers>
</configuration>

5.7 测试

package com.xuweiwei.mybatis.test;

import com.xuweiwei.mybatis.pojo.Employee;
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;

import java.io.IOException;
import java.io.InputStream;

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);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            Employee employee = (Employee) session.selectOne("com.xuweiwei.mybatis.pojo.Employee.selectEmployeeById", 1);
            System.out.println(employee);
        } finally {
            session.close();
        }

    }

}

6 接口编程

6.1 编写EmployeeMapper.java

package com.xuweiwei.mybatis.mapper;

import com.xuweiwei.mybatis.pojo.Employee;

public interface EmployeeMapper {

    public Employee getEmployeeById(Integer id);
}

6.2 修改EmployeeMapper.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="com.xuweiwei.mybatis.mapper.EmployeeMapper">
    <select id="getEmployeeById" resultType="com.xuweiwei.mybatis.pojo.Employee">
        select id,last_name lastName,gender,email  from employee where id = #{id}
    </select>
</mapper>

6.3 测试

package com.xuweiwei.mybatis.test;

import com.xuweiwei.mybatis.mapper.EmployeeMapper;
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;

import java.io.IOException;
import java.io.InputStream;

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);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            System.out.println(employeeMapper.getEmployeeById(1));
        } finally {
            session.close();
        }

    }

}

7 SqlSession

  • SqlSession的实例不是线程安全的,因此不能共享。
  • SqlSession每次使用完之后必须正确的关闭。

8 全局配置文件

  • 在全局配置文件中可以通过settings设置是否开启驼峰规则映射。
  • Employee.java
package com.xuweiwei.mybatis.pojo;

public class Employee {
    private Integer id;
    private String lastName;
    private String gender;
    private String email;

    public Integer getId() {
        return id;
    }

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

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    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;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName='" + lastName + '\'' +
                ", gender='" + gender + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}
  • mybatis-config.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>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/xuweiwei/mybatis/mapper/EmployeeMapper.xml"/>
    </mappers>
</configuration>
  • log4j.properties
og4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=debug, stdout 
  • EmployeeMapper.java
package com.xuweiwei.mybatis.mapper;

import com.xuweiwei.mybatis.pojo.Employee;

public interface EmployeeMapper {

    public Employee getEmployeeById(Integer id);
}
  • EmployeeMapper.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="com.xuweiwei.mybatis.mapper.EmployeeMapper">
    <select id="getEmployeeById" resultType="com.xuweiwei.mybatis.pojo.Employee">
        select id,last_name ,gender,email  from employee where id = #{id}
    </select>
</mapper>
  • 测试
package com.xuweiwei.mybatis.test;

import com.xuweiwei.mybatis.mapper.EmployeeMapper;
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;

import java.io.IOException;
import java.io.InputStream;

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);
        SqlSession session = sqlSessionFactory.openSession();
        try {
            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            System.out.println(employeeMapper.getEmployeeById(1));
        } finally {
            session.close();
        }

    }

}

Mybatis (一)的更多相关文章

  1. 【分享】标准springMVC+mybatis项目maven搭建最精简教程

    文章由来:公司有个实习同学需要做毕业设计,不会搭建环境,我就代劳了,顺便分享给刚入门的小伙伴,我是自学的JAVA,所以我懂的.... (大图直接观看显示很模糊,请在图片上点击右键然后在新窗口打开看) ...

  2. Java MyBatis 插入数据库返回主键

    最近在搞一个电商系统中由于业务需求,需要在插入一条产品信息后返回产品Id,刚开始遇到一些坑,这里做下笔记,以防今后忘记. 类似下面这段代码一样获取插入后的主键 User user = new User ...

  3. [原创]mybatis中整合ehcache缓存框架的使用

    mybatis整合ehcache缓存框架的使用 mybaits的二级缓存是mapper范围级别,除了在SqlMapConfig.xml设置二级缓存的总开关,还要在具体的mapper.xml中开启二级缓 ...

  4. 【SSM框架】Spring + Springmvc + Mybatis 基本框架搭建集成教程

    本文将讲解SSM框架的基本搭建集成,并有一个简单demo案例 说明:1.本文暂未使用maven集成,jar包需要手动导入. 2.本文为基础教程,大神切勿见笑. 3.如果对您学习有帮助,欢迎各种转载,注 ...

  5. mybatis plugins实现项目【全局】读写分离

    在之前的文章中讲述过数据库主从同步和通过注解来为部分方法切换数据源实现读写分离 注解实现读写分离: http://www.cnblogs.com/xiaochangwei/p/4961807.html ...

  6. MyBatis基础入门--知识点总结

    对原生态jdbc程序的问题总结 下面是一个传统的jdbc连接oracle数据库的标准代码: public static void main(String[] args) throws Exceptio ...

  7. Mybatis XML配置

    Mybatis常用带有禁用缓存的XML配置 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE ...

  8. MyBatis源码分析(一)开篇

    源码学习的好处不用多说,Mybatis源码量少.逻辑简单,将写个系列文章来学习. SqlSession Mybatis的使用入口位于org.apache.ibatis.session包中的SqlSes ...

  9. (整理)MyBatis入门教程(一)

    本文转载: http://www.cnblogs.com/hellokitty1/p/5216025.html#3591383 本人文笔不行,根据上面博客内容引导,自己整理了一些东西 首先给大家推荐几 ...

  10. MyBatis6:MyBatis集成Spring事物管理(下篇)

    前言 前一篇文章<MyBatis5:MyBatis集成Spring事物管理(上篇)>复习了MyBatis的基本使用以及使用Spring管理MyBatis的事物的做法,本文的目的是在这个的基 ...

随机推荐

  1. centos perl: symbol lookup error: /usr/local/lib64/perl5/auto/DBD/mysql/mysql.so: undefined symbol: mysql_init

    之前在安装天兔数据库监控工具lepus的时候,运行时一直报perl: symbol lookup error: /usr/local/lib64/perl5/auto/DBD/mysql/mysql. ...

  2. Zabbix实战-简易教程系列

    一.基础篇(安装和接入) Zabbix实战-简易教程--总流程  Zabbix实战-简易教程--整体架构图 Zabbix实战-简易教程--DB安装和表分区 Zabbix实战-简易教程--Server端 ...

  3. Angular整合zTree

    1 前提准备 1.1 新建一个angular4项目 参考博文:点击前往 1.2 去zTree官网下载zTree zTree官网:点击前往 三少使用的版本:点击前往 2 编程步骤 从打印出zTree对象 ...

  4. Ubuntu下配置ShadowS + Chrome

    // 这是一篇导入进来的旧博客,可能有时效性问题. 题目和全文中的ShadowS指代以ShadowS开头名字的某工具,以预防文章被和谐.本机Ubuntu 14.04 LTS.在apt-get upda ...

  5. Hadoop日志以及日志的格式和命名组成

    一.日志的格式 有两种日志,分别以log和out结尾 1)以log结尾的日志: 通过log4j日志记录格式进行记录的日志,采用的日常滚动文件后缀策略来命名日志文件,内容比较全. 2)以out结尾的日志 ...

  6. JAVA获取客户端IP地址和MAC地址

    1.获取客户端IP地址 public String getIp(HttpServletRequest request) throws Exception { String ip = request.g ...

  7. SQL强化(一)保险业务

    保险业务 : 表结构 : sql语句 : /*1. 根据投保人电话查询出投保人 姓名 身份证号 所有保单 编号 险种 缴费类型*/SELECTt2.cust_name,t2.idcard,t4.pro ...

  8. 狗书无敌,天下第一(flask基础)

    为什么选择使用flask? 和其他框架相比, Flask 之所以能脱颖而出,原因在于它让开发者做主,使其能对程序具有全面的创意控制. 在 Flask 中,你可以自主选择程序的组件,如果找不到合适的,还 ...

  9. mysql习题

    如图表创建数据库. create table class( cid int auto_increment primary key, caption ) )engine=innodb default c ...

  10. Spark算子--flatMapValues

    转载请标明出处http://www.cnblogs.com/haozhengfei/p/e7a46cecc65720997392516d553d9891.html flatMapValues--Tra ...