Mybatis使用之环境搭建

Mybatis使用之环境搭建

一:简介

集成环境:IntellijIDEA 14.0+Maven+Mybatis3.2.8+mysql。

主要为后续Mybatis使用搭建运行环境。

二:前期准备

1、 主要是数据库对应测试表的创建、这些表是后面学习过程中使用的表。数据模型简要ER图如下:

2、 建表语句以及初始化数据、见补充部分。

三:具体步骤

1、步骤概览:

2、具体过程:

i、 Maven引入依赖

    <properties>
        <junit.version>4.1</junit.version>
        <testng.version>6.8.8</testng.version>
        <sources.plugin.verion>2.1.1</sources.plugin.verion>
        <org.springframework>4.1.1.RELEASE</org.springframework>
        <servlet-api>3.1.0</servlet-api>
        <jsp-api>2.0</jsp-api>
        <javax.inject>1</javax.inject>
        <javax.el>2.2.4</javax.el>
        <org.hibernate>5.0.2.Final</org.hibernate>
        <org.aspectj>1.7.4</org.aspectj>
        <c3p0.version>0.9.1.2</c3p0.version>
        <mysql.version>5.1.34</mysql.version>
        <slf4j.version>1.7.10</slf4j.version>
        <spring.ldap.version>2.0.2.RELEASE</spring.ldap.version>
        <commons.pool>1.6</commons.pool>
        <mybatis.version>3.2.8</mybatis.version>
    </properties>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

ii、 配置数据库连接资源文件

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/scattered-items
jdbc.username=root
jdbc.password=root

编写数据库映射接口及方法、以AuthorMapper为例:

public interface AuthorMapper {

    int addAuthor(Author author);

    int deleteAuthor(int id);

    int updateAuthor(Author author);

    List<Author> getAllAuthors();

    int getAllAuthorsCount();
}

编写与数据库表对应实体、以Author为例:

@SuppressWarnings("unused")
public class Author {
    private int id;
    private String username;
    private String password;
    private String email;
    private String bio;
    private String favouriteSection;

    //省略getter setter...

    @Override
    public String toString() {
        return "Author{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", bio='" + bio + '\'' +
                ", favouriteSection='" + favouriteSection + '\'' +
                '}';
    }
}

iii、 配置mybatis整体配置文件

<?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 -->
    <properties resource="properties/jdbc.properties"/>

    <!--settings
    <settings>
        <setting name="cacheEnabled" value="true"/>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="multipleResultSetsEnabled" value="true"/>
        <setting name="useColumnLabel" value="true"/>
        <setting name="useGeneratedKeys" value="false"/>
        <setting name="autoMappingBehavior" value="PARTIAL"/>
        <setting name="defaultExecutorType" value="SIMPLE"/>
        <setting name="defaultStatementTimeout" value="25"/>
        <setting name="safeRowBoundsEnabled" value="false"/>
        <setting name="mapUnderscoreToCamelCase" value="false"/>
        <setting name="localCacheScope" value="SESSION"/>
        <setting name="jdbcTypeForNull" value="OTHER"/>
        <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
    </settings>-->

    <!--A type alias is simply a shorter name for a Java type.-->
    <typeAliases>
        <!--<typeAlias type="org.alien.mybatis.samples.model.Employee" alias="Employee"/>-->
        <!--<typeAlias type="org.alien.mybatis.samples.model.Department" alias="Department"/>-->

        <!--That is domain.blog.Author will be registered as author. If the @Alias annotation is found its value will be
            used as an [email protected]("author")-->
        <package name="org.alien.mybatis.samples.model"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driverClassName}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--<mapper resource="config/mappers/Department.xml"/>-->
        <!--<mapper resource="config/mappers/Employee.xml"/>-->
        <!--<mapper resource="org/alien/mybatis/samples/config/Department.xml"/>-->
        <!--<mapper class="org.alien.mybatis.samples.dao.DepartmentMapper"/>-->
        <!-- Register all interfaces in a package as mappers -->
        <package name="org.alien.mybatis.samples.mapper"/>
    </mappers>
</configuration>

iv、 配置mybatis映射文件

这里注意映射文件所放置的位置:resources/org/alien/mybatis/samples/mapper/AuthorMapper.xml。目的是为了在项目被编译之后AuthorMapper.xml文件是与AuthorMapper在同一文件夹内。至于为什么必须这样、后面会有。

<?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="org.alien.mybatis.samples.mapper.AuthorMapper">

    <resultMap id="author" type="author">
        <id property="id" column="author_id"/>
        <result property="username" column="username"/>
        <result property="password" column="password"/>
        <result property="email" column="email"/>
        <result property="bio" column="bio"/>
        <result property="favouriteSection" column="favouriteSection"/>
    </resultMap>

    <insert id="addAuthor" parameterType="author">
        INSERT INTO author(id, username) VALUES (#{id}, #{username})
        <selectKey keyProperty="id" resultType="int">
            SELECT max(id) FROM author
        </selectKey>
    </insert>

    <delete id="deleteAuthor" parameterType="int">
        DELETE FROM author
        WHERE id = #{id}
    </delete>

    <update id="updateAuthor" parameterType="author">
        UPDATE author
        SET username = #{username}
    </update>

    <select id="getAllAuthors" resultType="author">
        SELECT
            t.id,
            t.username,
            t.password,
            t.email,
            t.bio,
            t.favourite_section favouriteSection
        FROM author t
    </select>

    <select id="getAllAuthorsCount" resultType="int">
        SELECT count(1)
        FROM author
    </select>
</mapper>

配置日志文件(主要用于打印sql语句)

### set log levels ###
log4j.rootLogger =   , console

###  output to the console ###
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [%l]-[%p] %m%n

log4j.logger.org.alien.mybatis.samples.mapper=debug

vi、 AuthorServiceImpl:

/**
 * Created by andychen on 2015/5/18.<br>
 * Version 1.0-SNAPSHOT<br>
 */
public class AuthorServiceImpl implements AuthorService {

    /**
     * Add author info.
     *
     * @param author author instance
     * @return The key of current record in database.
     */
    @Override
    public int addAuthor(Author author) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            AuthorMapper authorMapper = sqlSession.getMapper(AuthorMapper.class);
            int authorId = authorMapper.addAuthor(author);
            sqlSession.commit();
            return authorId;
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    /**
     * Delete author info by author's id.
     *
     * @param authorId author id
     * @return int The number of rows affected by the delete.
     */
    @Override
    public int deleteAuthor(int authorId) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            AuthorMapper authorMapper = sqlSession.getMapper(AuthorMapper.class);
            int result = authorMapper.deleteAuthor(authorId);
            sqlSession.commit();
            return result;
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    /**
     * update author info
     *
     * @param author Author instance
     * @return int The number of rows affected by the update.
     */
    @Override
    public int updateAuthor(Author author) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            AuthorMapper authorMapper = sqlSession.getMapper(AuthorMapper.class);
            int result = authorMapper.updateAuthor(author);
            sqlSession.commit();
            return result;
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    /**
     * Query all authors
     *
     * @return all authors
     */
    @Override
    public List<Author> getAllAuthors() {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            AuthorMapper authorMapper = sqlSession.getMapper(AuthorMapper.class);
            return authorMapper.getAllAuthors();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    /**
     * Query all authors count
     *
     * @return all authors count
     */
    @Override
    public int getAllAuthorsCount() {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            AuthorMapper authorMapper = sqlSession.getMapper(AuthorMapper.class);
            return authorMapper.getAllAuthorsCount();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }
}

vii、 测试AuthorService接口:

public class AuthorServiceImplTest {
    private AuthorService authorService;

    @Before
    public void setUp() throws Exception {
        authorService = new AuthorServiceImpl();
    }

    @Test
    public void testGetAllAuthors() throws Exception {
        Assert.assertEquals(true, authorService.getAllAuthors().size() > 0);
    }

    @Test
    public void getAllAuthorsCount() throws Exception {
        Assert.assertEquals(true, authorService.getAllAuthorsCount() > 0);
    }

    @Test
    public void testAddAuthor() throws Exception {
        Assert.assertEquals(true, authorService.addAuthor(new Author(3, "year")) > 0);
    }

    @Test
    public void testDeleteAuthor() throws Exception {
        Assert.assertEquals(true, authorService.deleteAuthor(3) > 0);
    }

    @Test
    public void testUpdateAuthor() throws Exception {
        Assert.assertEquals(true, authorService.updateAuthor(new Author(2, "star_year")) > 0);
    }
}

四:补充

更多内容:Mybatis 目录

github地址:https://github.com/andyChenHuaYing/scattered-items/tree/master/items-mybatis

源码下载地址:http://download.csdn.net/detail/chenghuaying/8713311

MybatisUtil类:

/**
 * Loading mybatis config and mappers file.
 * Created by andychen on 2015/5/7.<br>
 * Version 1.0-SNAPSHOT<br>
 */
public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory;

    /**
     * Singleton model to get SqlSessionFactory instance.
     *
     * @return SqlSessionFactory instance
     */
    public static SqlSessionFactory getSqlSessionFactory() {
        String mybatisConfigPath = "config/mybatis/mybatis.xml";
        try {
            InputStream inputStream = Resources.getResourceAsStream(mybatisConfigPath);
            if (sqlSessionFactory == null) {
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqlSessionFactory;
    }

    /**
     * Open a SqlSession via SqlSessionFactory.
     * By the way, you should close the SqlSession in your code.
     *
     * @return SqlSession sqlSession instance.
     */
    public static SqlSession getSqlSession() {
        return MybatisUtil.getSqlSessionFactory().openSession();
    }
}

建表SQL语句:

/*
Navicat MySQL Data Transfer

Source Server         : scattered-items
Source Server Version : 50096
Source Host           : localhost:3306
Source Database       : scattered-items

Target Server Type    : MYSQL
Target Server Version : 50096
File Encoding         : 65001

Date: 2015-05-16 12:30:10
*/

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `author`
-- ----------------------------
DROP TABLE IF EXISTS `author`;
CREATE TABLE `author` (
  `ID` int(11) NOT NULL auto_increment,
  `USERNAME` varchar(200) default NULL,
  `PASSWORD` varchar(200) default NULL,
  `EMAIL` varchar(200) default NULL,
  `BIO` varchar(200) default NULL,
  `FAVOURITE_SECTION` varchar(200) default NULL,
  PRIMARY KEY  (`ID`),
  UNIQUE KEY `AUTHOR_INDEX` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of author
-- ----------------------------
INSERT INTO author VALUES ('1', 'alien', 'alien', '[email protected]', null, 'java io');

-- ----------------------------
-- Table structure for `blog`
-- ----------------------------
DROP TABLE IF EXISTS `blog`;
CREATE TABLE `blog` (
  `ID` int(11) NOT NULL auto_increment,
  `TITLE` varchar(200) default NULL,
  `AUTHOR_ID` int(11) default NULL,
  PRIMARY KEY  (`ID`),
  UNIQUE KEY `BLOG_INDEX` (`ID`),
  KEY `BLOG_AUTHOR_FG` (`AUTHOR_ID`),
  CONSTRAINT `BLOG_AUTHOR_FG` FOREIGN KEY (`AUTHOR_ID`) REFERENCES `author` (`ID`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of blog
-- ----------------------------
INSERT INTO blog VALUES ('1', 'Mybatis tutorial', '1');

-- ----------------------------
-- Table structure for `post`
-- ----------------------------
DROP TABLE IF EXISTS `post`;
CREATE TABLE `post` (
  `ID` int(11) NOT NULL auto_increment,
  `BLOG_ID` int(11) default NULL,
  `AUTHOR_ID` int(11) default NULL,
  `CREATED_ON` date default NULL,
  `SECTION` varchar(200) default NULL,
  `SUBJECT` varchar(200) default NULL,
  `DRAFT` varchar(200) default NULL,
  `BODY` varchar(200) default NULL,
  PRIMARY KEY  (`ID`),
  UNIQUE KEY `POST_INDEX` (`ID`),
  KEY `POST_BLOG_FG` (`BLOG_ID`),
  CONSTRAINT `POST_BLOG_FG` FOREIGN KEY (`BLOG_ID`) REFERENCES `blog` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of post
-- ----------------------------
INSERT INTO post VALUES ('1', '1', '1', '2015-05-16', 'Mybatis introduction', 'Mybatis', 'Mybatis series draft', 'How to lean mybatis ?');

-- ----------------------------
-- Table structure for `post_comment`
-- ----------------------------
DROP TABLE IF EXISTS `post_comment`;
CREATE TABLE `post_comment` (
  `ID` int(11) NOT NULL auto_increment,
  `POST_ID` int(11) default NULL,
  `NAME` varchar(200) default NULL,
  `COMMENT_TEXT` varchar(200) default NULL,
  PRIMARY KEY  (`ID`),
  UNIQUE KEY `POST_COMMENT_INDEX` (`ID`),
  KEY `POST_COMMENT_POST_FG` (`POST_ID`),
  CONSTRAINT `POST_COMMENT_POST_FG` FOREIGN KEY (`POST_ID`) REFERENCES `post` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of post_comment
-- ----------------------------
INSERT INTO post_comment VALUES ('1', '1', 'comment', 'Keep updating');

-- ----------------------------
-- Table structure for `post_tag`
-- ----------------------------
DROP TABLE IF EXISTS `post_tag`;
CREATE TABLE `post_tag` (
  `ID` int(11) NOT NULL auto_increment,
  `POST_ID` int(11) NOT NULL,
  `TAG_ID` int(11) NOT NULL,
  PRIMARY KEY  (`ID`),
  UNIQUE KEY `POST_TAG_INDEX` (`ID`),
  KEY `POST_TAG_INDEX2` (`POST_ID`),
  KEY `POST_TAG_INDEX3` (`TAG_ID`),
  CONSTRAINT `POST_TAG_TAG` FOREIGN KEY (`TAG_ID`) REFERENCES `tag` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `POST_TAG_POST` FOREIGN KEY (`POST_ID`) REFERENCES `post` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of post_tag
-- ----------------------------
INSERT INTO post_tag VALUES ('1', '1', '1');
INSERT INTO post_tag VALUES ('2', '1', '2');
INSERT INTO post_tag VALUES ('3', '1', '5');

-- ----------------------------
-- Table structure for `tag`
-- ----------------------------
DROP TABLE IF EXISTS `tag`;
CREATE TABLE `tag` (
  `ID` int(11) NOT NULL auto_increment,
  `NAME` varchar(200) default NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tag
-- ----------------------------
INSERT INTO tag VALUES ('1', 'Mybatis');
INSERT INTO tag VALUES ('2', 'Java');
INSERT INTO tag VALUES ('3', 'JavaScript');
INSERT INTO tag VALUES ('4', 'Web');
INSERT INTO tag VALUES ('5', 'ORM framework');
INSERT INTO tag VALUES ('6', null);

项目整体结构:

时间: 2024-10-08 20:05:14

Mybatis使用之环境搭建的相关文章

Java Web开发SpringMVC和MyBatis框架开发环境搭建和简单实用

1.下载SpringMVC框架架包,下载地址: 点击下载 点击打开地址如图所示,点击下载即可 然后把相关的jar复制到lib下导入 2.MyBatis(3.4.2)下载 点击下载 MyBatis中文文档地址 点击查看 下载解压之后把jar复制到lib下导入,大概是这样子的 3.jdbc连接库还没有下载...这个是5.1.41版本的... 点击下载 解压之后这样子... 4.fastjson 阿里巴巴的json解析库 点击下载 版本是1.2.24 这个是托管到了github上面的,地址是:点击进入

Spring+SpringMVC+mybatis入门(环境搭建+crud)

大学毕业快一年了,在学校里做了一个android APP的项目,一直都只是熟悉android后台开发是最大的短板,工作后,公司都是自己的框架,这种开源框架基本也没时间去接触.app和后台都是基于公司的平台开发,我觉得一个人做也没有啥难度.一直在混日子,把整个app的架构分析了一遍.后来公司业务需求,我被迫PC端和android客户端都的做.真心现在啥都不是研究的很深.心累.吐槽完毕.接下来,记录我自己学习ssm框架完成crud的整个过程. 一.开发环境搭建 1.新建一个动态web项目 点击完成工

mybatis springmvc velocity环境搭建

前言 轻量级ORM框架MyBatis完美的配合SpringMVC web框架实现了后台action的开发,结合Java模版引擎velocity实现了Java代码与前端代码的隔离. 搭建过程 后台配置mybatis 添加依赖 Spring 3.2.4-RELEASE <dependency>             <groupId>org.springframework</groupId>             <artifactId>spring-web

mybatis介绍与环境搭建

一.不用纯jdbc的原因,即缺点. 1.数据库理解,使用时创建,不用时释放,会对数据库进行频繁的链接开启和关闭,造成数据库的资源浪费,影响数据库的性能.设想:使用数据库的连接池.2.将sql语句硬编码到java代码中,不利于系统维护.设想:将sql放到配置文件中.3.向preparedstatement中设置参数,对占位符位置和设置参数值,硬编码在Java代码中,不利于系统维护.设想:将sql语句及占位符配置到xml中.4.从resultset中便利结果集时,存在硬编码,将获取表的字段进行硬编码

mybatis学习之环境搭建&amp;入门实例

mybatis:3.2.8 数据库:mysql 项目结构 jar包准备: mybatis-3.2.8.jar mysql-connector-java-5.1.39-bin.jar 配置文件 1.jdbc.properties配置文件: jdbc.driverClassName = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://127.1.0.1:3306/db_mybatis jdbc.username=root jdbc.password=roo

MyBatis(一) —— 环境搭建

一 什么是 MyBatis? MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型.接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录.(官方解释) 二 为什么使用MyBatis? 1. MyBatis简单实用 MyBatis使用难度相对简单,仅仅需要导

springboot整合mybatis(SSM开发环境搭建)

0.项目结构: 1.application.properties中配置整合mybatis的配置文件.mybatis扫描别名的基本包与数据源 server.port=80 logging.level.org.springframework=DEBUG #springboot mybatis #jiazai mybatis peizhiwenjian mybatis.mapper-locations = classpath:mapper/*Mapper.xml mybatis.config-loca

spring+springMVC+mybatis+maven+mysql环境搭建(二)

上一篇整合了spring+mybatis,基本上还不是web工程,接下来接入springMVC,Let's go! 一.工程转换成Web工程 首先右击项目-->properties-->project facets,观察是否出现下图配置 没出现也不要慌张,先把Dynamic Web Module√去掉,然后点击ok,再次右击项目,进入priperties-->project facets,勾上Dynamic Web Module,该配置就出现了,点击箭头所指,进入下图界面: 这时发现新增

Mybatis学习(1)开发环境搭建

什么是mybatis MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索.MyBatis使用简单的XML或注解用于配置和原始映射,将接口和Java的POJOs(Plan Old Java Objects,普通的Java对象)映射成数据库中的记录. orm工具的基本思想 无论是用过的hibernate,mybatis,你都可以法相他们有一个共同点: 1. 从配置文件(通常是XML配置文件中)得到 ses