关闭

Mybatis入门

标签: javamybatis
125人阅读 评论(0) 收藏 举报
分类:

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



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2396次
    • 积分:141
    • 等级:
    • 排名:千里之外
    • 原创:12篇
    • 转载:1篇
    • 译文:0篇
    • 评论:3条
    文章分类
    最新评论