Maven+mybatis+mysql项目实践(附demo)

Maven+mybatis+mysql项目实践(附demo)

准备工作
- Maven搭建与工程建立(参考http://blog.csdn.net/kevinbetterq/article/details/77967856)
- mysql安装

接下来我们的项目在我上一篇Maven创建Web项目的基础上进行添加:
( 文章末尾附上实现的一个demo )


1、数据库建测试表

Maven+mybatis+mysql项目实践(附demo)_第1张图片

2、修改pom.xml文件

添加以下代码,加入依赖:

<dependencies>
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>5.1.38version>
    dependency>
    <dependency>
        <groupId>org.apache.logging.log4jgroupId>
        <artifactId>log4j-coreartifactId>
        <version>2.6.1version>
    dependency>
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatisartifactId>
        <version>3.4.1version>
    dependency>
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.10version>
    dependency>
dependencies>

完整pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <groupId>com.qwkgroupId>
    <artifactId>spring_mybatis_1artifactId>
    <version>0.0.1-SNAPSHOTversion>
    <packaging>warpackaging>

    <dependencies>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.38version>
        dependency>
        <dependency>
            <groupId>org.apache.logging.log4jgroupId>
            <artifactId>log4j-coreartifactId>
            <version>2.6.1version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.4.1version>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.10version>
        dependency>
    dependencies>
project>

3、创建实体类,配合数据库

这里写图片描述

package com.qwk.entity;
public class Book {

    private int id;
    private String bookName;

    public int getId() {
        return id;
    }

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

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

}

4、创建访问接口 BookDaoI.java

这里写图片描述

package com.qwk.dao;
import java.util.List;
import com.qwk.entity.*;

public interface BookDaoI {
    public List getAllBook();
}

5、新建映射文件 BookMapper.xml

这里写图片描述




<mapper namespace="com.qwk.dao.BookDaoI">
    <select id="getAllBook" parameterType="int" resultType="Book">
        select * from tb_book 
    select>
mapper>

6、新建MyBatis配置文件 MyBatisCfg.xml

Maven+mybatis+mysql项目实践(附demo)_第2张图片

  • 新增db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=123456
  • 新增MyBatisCfg.xml


<configuration>
    
     <properties resource="db.properties">properties> 

    
    <typeAliases>
        <package name="com.qwk.entity"/>
    typeAliases>

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


    <mappers>
        
        <mapper resource="com/qwk/mapper/BookMapper.xml" />
    mappers>
configuration>

7、新增MyBatisUtil工具类

这里写图片描述

package com.qwk.util;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


public class MyBatisUtil {

    /**
     * 获取SqlSessionFactory
     * @return SqlSessionFactory
     */
    public static SqlSessionFactory getSqlSessionFactory() {
        String resource = "MyBatisCfg.xml";
        InputStream is = MyBatisUtil.class.getClassLoader().getResourceAsStream(resource);
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        return factory;
    }

    /**
     * 获取SqlSession
     * @return SqlSession
     */
    public static SqlSession getSqlSession() {
        return getSqlSessionFactory().openSession();
    }

    /**
     * 获取SqlSession
     * @param isAutoCommit 
     *         true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务
     *         false 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务
     * @return SqlSession
     */
    public static SqlSession getSqlSession(boolean isAutoCommit) {
        return getSqlSessionFactory().openSession(isAutoCommit);
    }
}

8、创建Impl类实现接口

这里写图片描述

package com.qwk.dao.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.qwk.dao.BookDaoI;
import com.qwk.entity.Book;
import com.qwk.util.MyBatisUtil;

public class BookImpl implements BookDaoI{

    public List getAllBook() {
        //获得会话对象
        SqlSession session= MyBatisUtil.getSqlSession(true); 
        try {          
            BookDaoI bookDao = session.getMapper(BookDaoI.class);
            return bookDao.getAllBook();
        } finally {
            session.close();
        }
    }
}

9、新增log4j2.xml配置文件

可以进行日志的记录,因为前面的导入,不添加的话项目会出现错误
Maven+mybatis+mysql项目实践(附demo)_第3张图片



<Configuration status="off" monitorInterval="1800">    
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        Console>        
    Appenders>

    <Loggers>            
        <Root level="debug">
            <AppenderRef ref="Console" />
        Root>
    Loggers>
Configuration>

测试: 创建类TestBookImpl.java

这里写图片描述

package com.qwk.test;

import static org.junit.Assert.*;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import com.qwk.dao.BookDaoI;
import com.qwk.dao.impl.BookImpl;
import com.qwk.entity.Book;

public class TestBookImpl {
    static BookDaoI bookDao;

    @BeforeClass
    public static void beforeClass() {
        bookDao = new BookImpl();
    }

    @Test
    public void testGetAllBookTypes(){
        List books = bookDao.getAllBook();
        for(Book book:books){
            System.out.println(book.getBookName());
        }
        assertNotNull(books);
    }
}

项目右键->Run As->JUnit Test,可以看到成功输出

这里写图片描述


这样就实现了 Maven+mybatis+mysql 的一个小项目实例了!!

感受:
mybatis与直接的JDBC区别,就在于mybatis将对数据库的sql语句访问都放在了一个配置文件中,这样拆分了代码部分,只需要配置一下就可以实现数据库的sql访问了。


后续还会继续整合Spring和SpringMVC,大家有需要可以看一下:
Spring整合MyBatis(Maven+spring+MyBatis+mysql实践附demo)
SSM框架整合(Maven+Spring+SpringMVC+Mybatis+mysql 附demo实例)

最后附上我的github源码,一个mybatis连接mysql的小demo:
https://github.com/KevinBetterQ/SpringMVC_Mybatis/tree/517b1d1b6f442d8f567ef72212d137213c5bb05f

你可能感兴趣的:(JavaWeb)