Mybatis 基本用法

导入三个包

Mysql mysql-connector-java-5.1.39-bin.jar
Mybatis mybatis-3.4.6.jar
打印日志 log4j-1.2.17.jar

Mybatis可用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>

    <!-- 引入properties文件,里面存放driver,url,username,password的数据库信息 -->
    <properties resource="mysql.properties"/>

    <!-- 为类设置别名,否则在mapper配置中要输入完整包名 -->
    <typeAliases>
        <typeAlias alias="customer" type="com.shpun.entity.Customer"/>
    </typeAliases>

    <!-- 配置数据库信息 -->
    <environments default="testCustoemr">
        <environment id="testCustomer">
            <transactionManager type="JDBC"></transactionManager>
            <!-- 使用数据库连接池 -->
            <dataSource type="POOLED">      
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

</configuration>

通过mybatis-config.xml构建SqlSessionFactory

package com.shpun.utils;
public class SqlSessionFactoryUtils {

    private final static Class<SqlSessionFactoryUtils> LOCK = SqlSessionFactoryUtils.class;

    private static SqlSessionFactory sqlSessionFactory;

    private SqlSessionFactoryUtils(){}

    public static SqlSessionFactory getSqlSessionFactory(){
        synchronized (LOCK){
            if(sqlSessionFactory != null){
                return sqlSessionFactory;
            }

            String resource = "mybatis-config.xml";
            InputStream inputStream;
            try {
                // 读取 mybatis-config.xml 配置文件
                inputStream = Resources.getResourceAsStream(resource);
                // 根据配置文件构建 SqlSessionFactory
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            }catch (Exception e){
                e.printStackTrace();
                return null;
            }
            return sqlSessionFactory;
        }
    }
    // 提供获取 SqlSession 的方法
    public static SqlSession openSqlSession(){
        if(sqlSessionFactory == null){
            getSqlSessionFactory();
        }
        return sqlSessionFactory.openSession();
    }
}

创建JavaBean Customer

package com.shpun.entity;
public class Customer {
    private String id;
    private String name;
    private String gender;
    private String birthday;
    private String tel;
    private String email;
    private String introduction;
    /*getter setter*/
}

定义映射器 需要Java接口和xml文件

创建CustomerMapper接口

package com.shpun.mapper;
public interface CustomerMapper {
    int insertCustomer(Customer customer);
    int deleteCustomer(String id);
    int updateCustomer(Customer customer);
    Customer selectCustomer(String id);
    List<Customer> selectAllCustomer();
}

创建CustomerMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- 使Mybatis能找到该接口 -->
<mapper namespace="com.shpun.mapper.CustomerMapper">

    <!-- 默认自动映射,即表column与JavaBean的变量名要一致,可通过加as实现 -->

    <!-- parameterType="customer" 传入的参数为customer,customer在mysql-config.xml中已经定义了别名
        若未定义,应完整包名com.shpun.entity.Customer
     -->
    <!--  useGeneratedKeys="true" 使用Statement的getGeneratedKeys()进行主键回填,获取新插入的主键
          keyProperty="id" 为填入 JavaBean 中的哪个属性 Customer 中为 id
    -->
    <insert id="insertCustomer" parameterType="customer" useGeneratedKeys="true" keyProperty="id">
        insert into customers (name,gender,birthday,tel,email,introduction) value (#{name},#{gender},#{birthday},#{tel},#{email},#{introduction})
    </insert>

    <!-- parameterType="string" 为系统定义别名 Java类型为 String -->
    <delete id="deleteCustomer" parameterType="string">
        delete from customers where id=#{id}
    </delete>

    <update id="updateCustomer" parameterType="customer">
        update customers set name=#{name},gender=#{gender},birthday=#{birthday},tel=#{tel},email=#{email},introduction=#{introduction} where id=#{id}
    </update>

    <select id="selectCustomer" parameterType="string" resultType="customer">
        select * from customers where id=#{id}
    </select>

    <select id="selectAllCustomer" resultType="customer">
        select * from customers
    </select>


    <!-- 定义结果集映射规则等 用于Select
          默认是自动映射,即表column与JavaBean属性名要一致,也可在select中用as修改,
          使用默认,则select中为resultType="customer"
          若要使用下列resuleMap,替换select中resultType="customer"为resultMap="customerMap"
   
    <resultMap id="customerMap" type="customer">
        <id property="id" column="id"></id>
        <result property="name" column="name"></result>
        <result property="gender" column="gender"></result>
        <result property="birthday" column="birthday"></result>
        <result property="tel" column="tel"></result>
        <result property="email" column="email"></result>
        <result property="introduction" column="introduction"></result>
    </resultMap>
    -->
</mapper>

创建完映射一定一定一定要到mybatis-config.xml中添加

    <!-- 配置完映射xml,需要在mybatis-config.xml中添加 -->
    <mappers>
        <mapper resource="com/shpun/mapper/CustomerMapper.xml"/>
    <!--
          或包名引入 则自动扫描
       <package name="com/shpun/mapper"/>
    -->
    </mappers>

mybatis-config.xml->工具类->JavaBean->Mapper的接口和xml文件

测试使用

        Logger log = Logger.getLogger(TestMybatis.class);    
        SqlSession sqlSession = null;

        try{

            // 获取SqlSeesion
            sqlSession = SqlSessionFactoryUtils.openSqlSession();
            // 获取Mapper
            CustomerMapper customerMapper = sqlSession.getMapper(CustomerMapper.class);
  
            log.info(customerMapper.selectAllCustomer());

          /* 增删改需要添加
            sqlSession.commit();
          */
        }catch (Exception e){
            e.printStackTrace();
          /* 增删改需要添加
            sqlSession.rollback();
          */
        }finally {
          // 使用完要关闭
            if(sqlSession != null){
                sqlSession.close();
            }
        }

使用log4j需要添加log4j.properties

log4j.rootLogger=DEBUG,stdout
log4j.logger.org.mybatis=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d %c: %m%n
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,734评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,931评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,133评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,532评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,585评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,462评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,262评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,153评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,587评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,792评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,919评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,635评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,237评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,855评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,983评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,048评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,864评论 2 354

推荐阅读更多精彩内容

  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,520评论 0 4
  • 1 Mybatis入门 1.1 单独使用jdbc编程问题总结 1.1.1 jdbc程序 上边使...
    哇哈哈E阅读 3,306评论 0 38
  • “恭喜你,重新获得了一次考取清北的机会,那些哈佛剑桥什么的你随便挑!”戴眼镜的推了推镜架,码字如飞,话语纷飞。 我...
    蒋血阅读 177评论 0 1
  • 小明第一天掉了20块 第二天他走在马路边捡到了30块 他很高兴 于是到一彩票店买彩票 花了30块 中了15块 他还...
    天体小力阅读 195评论 0 0
  • 黄小海_9cbe阅读 100评论 0 0