Idea中maven环境下搭建MyBatis项目

Posted AlexanderTheGreat

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Idea中maven环境下搭建MyBatis项目相关的知识,希望对你有一定的参考价值。

1、选择Maven框架下的webapp

1.1 添加新节点:archetypeCatalog=internal

1.2 或者在settings------->Build,Execution,Deployment——>Maven——>VM Options设置 -DarchetypeCatalog=internal

 

2、在Maven的pom文件中引入MyBatis需要用的jar包:

创建对应的java项目,引入需要的mybatis需要的jar,以及连接mysql数据库的jar!

asm-3.3.1.jar:操作Javaj字节码的类库

cglib-2.2.2.jar:用来动态集成Java类或实现接口

commons-logging-1.1.1.jar:用于通用日志处理

javassist-3.17.1-GA.jar:分析、编辑和创建Java字节码的类库

log4j-1.2.17.jar:日志系统

slf4j-api-1.7.5.jar:日志系统的封装,对外提供统一的API接口

slf4j-log4j12-1.7.5.jar:slf4j对log4j的对应驱动,完成slf4j绑定log4j

mybatis-3.2.2.jar

mysql-connector-java-5.1.7-bin.jar/3

<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/maven-v4_0_0.xsd">
    <parent>
        <artifactId>Book_08</artifactId>
        <groupId>cn.alexander</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>MyBatis</artifactId>
    <packaging>war</packaging>
    <name>MyBatis Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.3</version>
            <scope>test</scope>
        </dependency>


        <!--配置mybatis需要的依赖包-->
        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>3.3.1</version>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.17.1-GA</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.7</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.5</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>






    </dependencies>
    <build>
       <resources>
           <resource>
               <directory>src/main/java</directory>
               <includes>
                   <include>**/*.xml</include>
               </includes>
           </resource>
       </resources>
    </build>
</project>

 

3、创建MyBatis核心配置文件mybatis-config.xml

MyBatis核心配置文件主要用于配置数据库连接和MyBatis运行时所需的各种特性,包含了设置和影响MyBatis行为的属性。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTDConfig 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="jdbc.properties"></properties>
    <settings>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="true"></setting>
    </settings>
   <!-- <settings>
        <setting name="autoMappingBehavior" value="NONE"/>
    </settings>-->
    <typeAliases>
    <package name="cn.alexander.entity"></package>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <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>
    <mappers>
      <!--  <mapper resource="cn/alexander/dao/IStudentDAO.xml"/>-->
        <package name="cn.alexander.dao"></package>
    </mappers>
</configuration>

4、创建数据库表

 

 5、在idea中创建实体类

package cn.alexander.entity;

import java.io.Serializable;


public class Dept implements Serializable {
    private Integer deptno;
    private String deptname;

    public Integer getDeptno() {
        return deptno;
    }

    public void setDeptno(Integer deptno) {
        this.deptno = deptno;
    }

    public String getDeptname() {
        return deptname;
    }

    public void setDeptname(String deptname) {
        this.deptname = deptname;
    }

    public Dept(Integer deptno, String deptname) {
        this.deptno = deptno;
        this.deptname = deptname;
    }

    public Dept(String deptname) {
        this.deptname = deptname;
    }

    public Dept() {
    }

    @Override
    public String toString() {
        return "Dept{" +
                "deptno=" + deptno +
                ", deptname=\'" + deptname + \'\\\'\' +
                \'}\';
    }
}

6、创建接口

package cn.alexander.dao;

import cn.alexander.entity.Dept;

import java.util.List;

public interface IDeptDAO {
    // 查询所有的部门
    public List<Dept> findAll();
}

7、创建接口的实现类

7.1使用单例创建seession

package cn.alexander.util;

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

import java.io.IOException;
import java.io.InputStream;

/**
 * SqlSessionFactory的单例类
 */
public class SessionFactoryUtil {
    // 创建需要单例的对象实例
    private static SqlSessionFactory sessionFactory;

    // 私有化构造
    private SessionFactoryUtil(){}

    // 对外提供访问接口
    public static synchronized SqlSession getSession(){
        try {
            InputStream stream = Resources.getResourceAsStream("mybatis-config.xml");
            // 判断SqlSessionFactory是否为空,如果为空则创建
            if(sessionFactory==null){
                sessionFactory = new SqlSessionFactoryBuilder().build(stream);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sessionFactory.openSession();
    }


}

7.2通过session实现方法

package cn.alexander.dao;

import cn.alexander.entity.Dept;
import cn.alexander.util.SessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class IDeptDAOImpl implements IDeptDAO {
    public List<Dept> findAll() {
        // 获取session
        SqlSession session = null;
        List<Dept> depts = null;
        try{
            session = SessionFactoryUtil.getSession();
            IDeptDAO mapper = session.getMapper(IDeptDAO.class);
            depts = mapper.findAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            session.close();
        }
        return depts;
    }
}

8、接口对应的配置文件

<?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">
<!--映射文件的根节点
  namespace
-->
<mapper namespace="cn.alexander.dao.IDeptDAO">
    <select id="findAll" resultType="Dept">
        select * from dept
    </select>
</mapper>

修改pom.xml中的build节点。保证即使不在resources文件夹下的配置文件也能被读取

 <build>
       <resources>
           <resource>
               <directory>src/main/java</directory>
               <includes>
                   <include>**/*.xml</include>
               </includes>
           </resource>
       </resources>
    </build>

 

9、主配置关联小配置

 在mybatis-config.xml中用mappers节点使主配置关联到小配置

 <mappers>
      <!--  <mapper resource="cn/alexander/dao/IStudentDAO.xml"/>-->
        <package name="cn.alexander.dao"></package>
    </mappers>

10、编写测试类

package cn.alexander.test;

import cn.alexander.dao.IDeptDAO;
import cn.alexander.dao.IDeptDAOImpl;
import cn.alexander.entity.Dept;
import org.apache.log4j.Logger;
import org.junit.Test;

import java.util.List;

public class Test20170923 {
    Logger logger = Logger.getLogger(Test20170923.class);
    @Test
    public void findAll(){
        IDeptDAO iDeptDAO = new IDeptDAOImpl();
        List<Dept> depts = iDeptDAO.findAll();
        logger.debug(depts);
    }
}

11、测试类运行结果:

 

以上是关于Idea中maven环境下搭建MyBatis项目的主要内容,如果未能解决你的问题,请参考以下文章

IDEA 搭建SpringBoot项目:SpringBoot + MyBatis + Druid +MyBatis-Generator

Mybatis环境搭建-实现查询所有的功能

IDEA下Scala Maven开发环境搭建

使用idea 搭建一个 SpringBoot + Mybatis + logback 的maven 项目

idea 搭建Spring Boot +Mybatis

idea+springboot+Mybatis搭建web项目