Mybatis入门

原创 2015年11月17日 16:37:56

  1. 项目依赖
  2. 创建domain类、dao接口、daoImpl类、mapper接口
  3. 从XML中读取SqlSessionFactory
  4. 测试类

项目依赖:

如果使用Maven来构建项目,那么在pom.xml文件中添加以下依赖:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.27</version>
</dependency>

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.3.0</version>
</dependency>


<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>


创建domain类、dao类、mapper类

创建domain类 -- Admin.java

package com.mob.domain;

/**
 * Created by jianwl on 2015/11/17.
 */
public class Admin {
    private Long id;
    private String userName;
    private String password;
    private String nickName;

    public Long getId() {
        return id;
    }

    public void setId(Long 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 getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }
}



创建dao接口 -- AdminDao.java


package com.mob.dao;

import com.mob.domain.Admin;
import org.apache.ibatis.session.SqlSession;

/**
 * Created by jianwl on 2015/11/17.
 */
public interface AdminDao {
    Admin getAdminById(SqlSession sqlSession,Long id);
}



创建daoImpl类 -- AdminDaoImpl.java


package com.mob.dao;

import com.mob.domain.Admin;
import com.mob.mapper.AdminMapper;
import org.apache.ibatis.session.SqlSession;

/**
 * Created by jianwl on 2015/11/17.
 */
public class AdminDaoImpl implements AdminDao {
    @Override
    public Admin getAdminById(SqlSession sqlSession, Long id) {
        AdminMapper mapper = sqlSession.getMapper(AdminMapper.class);
        return mapper.getAdminById(id);
    }
}


创建mapper接口 -- AdminMapper.java


package com.mob.mapper;

import com.mob.domain.Admin;
import org.apache.ibatis.session.SqlSession;

/**
 * Created by jianwl on 2015/11/17.
 */
public interface AdminMapper {
    Admin getAdminById(Long id);
}

从XML中读取SqlSessionFactory 

每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为中心的;SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得,然后通过SqlSessionFactory实例得到SqlSession;创建一个工具类MybatisUtil.java 获取SqlSessionFactory实例

public class MybatisUtil {
    private static final Logger logger = Logger.getLogger(MybatisUtil.class);

    private static SqlSessionFactory sqlSessionFactory_mybatis_W = null;

    private static final String CONF_MYBATIS_W = "db_mybatis_conf/mybatis-conf.xml"; 

    static {
        logger.info(">>>>>>>>>>>>>>>>>>>>>INIT MybatisUtil BEGIN<<<<<<<<<<<<<<<<<<<<<<");
        Reader rdr;

        try {
            rdr = Resources.getResourceAsReader(CONF_MYBATIS_W);
            sqlSessionFactory_mybatis_W = new SqlSessionFactoryBuilder().build(rdr);
            rdr.close();
        } catch (IOException e){
            e.printStackTrace();
        }


        logger.info(">>>>>>>>>>>>>>>>>>>INIT MybatisUtil FINSH<<<<<<<<<<<<<<<<<<<<<<<<<<<");
    }

    public static SqlSessionFactory getSqlSessionFactory_mybatis_W(){
        return sqlSessionFactory_mybatis_W;
    }


}


mybatis-conf.xml 配置文件


</pre><p><pre name="code" class="html"><?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 resource="mysql/config.properties"></properties>

    <typeAliases>
        <typeAlias type="com.mob.domain.Admin" alias="Admin"/>
    </typeAliases>

    <environments default="${environment}">
        <environment id="local">
            <transactionManager type="${transactionManager_type}"/>
            <dataSource type="${datasource_type}">
                <property name="driver" value="${driver}" />
                <property name="url" value="${hermes-url}" />
                <property name="username" value="${hermes-username}" />
                <property name="password" value="${hermes-password}" />
                <property name="poolMaximumIdleConnections" value="${jdbc.minPoolSize}" />
                <property name="poolMaximumActiveConnections" value="${jdbc.maxPoolSize}" />
                <property name="poolTimeToWait" value="${jdbc.maxIdleTime}" />
                <property name="poolPingQuery" value="SELECT NOW()" />
                <property name="poolPingEnabled" value="true" />
            </dataSource>
        </environment>
        <environment id="development">
            <transactionManager type="${transactionManager_type}"/>
            <dataSource type="${datasource_type}">
                <property name="driver" value="${driver}" />
                <property name="url" value="${interact-url}" />
                <property name="username" value="${hermes-username}" />
                <property name="password" value="${hermes-password}" />
                <property name="poolMaximumIdleConnections" value="${jdbc.minPoolSize}" />
                <property name="poolMaximumActiveConnections" value="${jdbc.maxPoolSize}" />
                <property name="poolTimeToWait" value="${jdbc.maxIdleTime}" />
                <property name="poolPingQuery" value="SELECT NOW()" />
                <property name="poolPingEnabled" value="true" />
            </dataSource>
        </environment>
        <environment id="production">
            <transactionManager type="${transactionManager_type}"/>
            <dataSource type="${datasource_type}">
                <property name="driver" value="${driver}" />
                <property name="url" value="${hermes-url}" />
                <property name="username" value="${hermes-username}" />
                <property name="password" value="${hermes-password}" />
                <property name="poolMaximumIdleConnections" value="${jdbc.minPoolSize}" />
                <property name="poolMaximumActiveConnections" value="${jdbc.maxPoolSize}" />
                <property name="poolTimeToWait" value="${jdbc.maxIdleTime}" />
                <property name="poolPingQuery" value="SELECT NOW()" />
                <property name="poolPingEnabled" value="true" />
            </dataSource>
        </environment>
    </environments>


    <mappers>
        <mapper resource="com/mob/mapper/AdminMapper.xml"/>
    </mappers>

</configuration>

config.properties 配置文件

</pre><pre name="code" class="html"><pre name="code" class="html">environment=local
logImpl=LOG4J
transactionManager_type=JDBC
datasource_type=POOLED
driver=com.mysql.jdbc.Driver

jdbc.initialPoolSize=1
jdbc.minPoolSize=1
jdbc.maxPoolSize=5
jdbc.acquireIncrement=1
jdbc.maxIdleTime=200
jdbc.checkoutTimeout=3000

# hermes
hermes-url=jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
hermes-username=root
hermes-password=123456


AdminMapper.xml 配置文件  (** 注意: namespace为AdminMapper接口的完全限定名,select中的id与接口中的方法名需一致)

<?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.mob.mapper.AdminMapper">
    <resultMap type="Admin" id="admin">
        <id property="id" column="id" />
        <result property="userName" column="user_name"/>
        <result property="password" column="password"/>
        <result property="nickName" column="nick_name"/>
    </resultMap>

    <select id="getAdminById" parameterType="long" resultMap="admin">
        SELECT *
        FROM admin
        WHERE id = #{value}
    </select>

</mapper>


测试类AdminTest

package com.mob.admin;


import com.mob.dao.AdminDaoImpl;
import com.mob.domain.Admin;
import com.mob.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.junit.Test;

/**
 * Created by jianwl on 2015/11/17.
 */
public class AdminTest {
    private static final Logger logger = Logger.getLogger(AdminTest.class);

    @Test
    public void getAdminById() {
        SqlSessionFactory sqlSessionFactory_mybatis_w = MybatisUtil.getSqlSessionFactory_mybatis_W();
        SqlSession sqlSession = sqlSessionFactory_mybatis_w.openSession();
        AdminDaoImpl adminDao = new AdminDaoImpl();
        Long id = 1L;
        try {
            Admin admin = adminDao.getAdminById(sqlSession, id);

            logger.info("id = " + admin.getId() + " username = " + admin.getUserName()
                            + " password = " + admin.getPassword() + " nickname = " + admin.getNickName()
            );
        } finally {
            sqlSession.close();
        }
    }
}



版权声明:本文为博主原创文章,未经博主允许不得转载。

mybatis从入门到精通

  • 2017年10月27日 12:04
  • 48.82MB
  • 下载

mybatis入门之二、使用接口interface

2.1 为何使用接口 interface 来编程**上一章用SqlSession实例来直接执行已映射的SQL语句: session.selectOne(“com.yihaomen.mybatis.m...

mybatis 入门文档

  • 2015年09月18日 11:56
  • 200KB
  • 下载

MyBatis3 快速入门

  • 2017年08月24日 22:45
  • 543KB
  • 下载

mybatis官网参考文档-入门(版本: 3.4.6-SNAPSHOT)

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML...

Mybatis入门程序

  • 2017年07月21日 23:17
  • 3.57MB
  • 下载

MyBatis入门详解

  • 2017年07月19日 09:37
  • 2.9MB
  • 下载

MyBatis 入门到精通(三) 高级结果映射

MyBatis的创建基于这样一个思想:数据库并不是您想怎样就怎样的。虽然我们希望所有的数据库遵守第三范式或BCNF(修正的第三范式),但它们不是。如果有一个数据库能够完美映射到所有应用程序,也将是非常...

mybatis入门实战之一

  • 2017年08月20日 21:45
  • 14KB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Mybatis入门
举报原因:
原因补充:

(最多只允许输入30个字)