Mybatis(一)--入门小demo

强烈推荐一个大神的人工智能的教程:http://www.captainbed.net/zhanghan

简介

     Mybatis的前身是iBATIS,是在2001年发起的一个开源项目,最初侧重于密码软件的开发,后来发展成为一款基于Java的持久层框架。

     Mybatis是一款优秀的支持自定义SQL查询、存储过程和高级映射的持久层框架。Mybatis可以使用XML或注解进行配置和映射,Mybatis通过将参数映射到配置的SQL形成最终执行的SQL语句,最后将执行SQL的结果集映射成JAVA对象返回。与其他ORM框架不同,Mybatis并没有将java对象与数据库表关联起来,而是将java方法和sql语句关联起来,所以我们可以使用一些数据库的特性或者视图等等,极大的提高了开发的灵活性。

创建demo

    1.使用idea进行开发

    2.创建一个maven工程,命名mybatis-zh

    ①新建工程

    

     ②设置坐标

      groupId:zh.mybatis

      artifactId:zh

      version:1.0-SNAPSHOT

     3.引入mybatis、mysql、日志相关的jar包   

<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.0</modelVersion>

  <groupId>zh.mybatis</groupId>
  <artifactId>zh</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>zh</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <!--mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.5</version>
    </dependency>

    <!--mysql-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>

    <!--日志-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.25</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.25</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    <!--junit-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

      4.在src/main/java下建立model,包名为zh.mybatis.simple.model,实体名称为Country    

package zh.mybatis.simple.model;

/**
 * Created by huan on 2017/12/26.
 */
public class Country {
    private Long id;
    private String countryname;
    private String countrycode;

    public Long getId() {
        return id;
    }

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

    public String getCountryname() {
        return countryname;
    }

    public void setCountryname(String countryname) {
        this.countryname = countryname;
    }

    public String getCountrycode() {
        return countrycode;
    }

    public void setCountrycode(String countrycode) {
        this.countrycode = countrycode;
    }
}

       5.在resources下创建mapper,包名为zh.mybatis.simple.mapper,mapper的名称为CountryMapper.xml

<?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="zh.mybatis.simple.mapper.CountryMapper">
    <select id="selectAll" resultType="Country">
        SELECT id,countryname,countrycode FROM country
    </select>
</mapper>

      6.在resources下创建mybatis的配置文件,名称为mybatis-config.xml

<?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>
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    
    <typeAliases>
        <package name="zh.mybatis.simple.model" />
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC">
                <property name="" value=""/>
            </transactionManager>
            <dataSource type="UNPOOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="zh/mybatis/simple/mapper/CountryMapper.xml"/>
    </mappers>
</configuration>

        7.在resources下创建log4j.properties

#全局变量
log4j.rootLogger = ERROR,stdout
#Mybatis 日志配置
log4j.logger.zh.mybatis.simple.mapper = TRACE
#控制台输出配置
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %5p [%t] - %m%n

      8.最后写一个测试类在test/java下创建包名为zh.mybatis.simple.mapper,类名为CountryMapperTest

package zh.mybatis.simple.mapper;

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 org.junit.BeforeClass;
import org.junit.Test;
import zh.mybatis.simple.model.Country;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

/**
 * Created by huan on 2017/12/26.
 */
public class CountryMapperTest {
    private static SqlSessionFactory sqlSessionFactory;

    @BeforeClass
    public static void init(){
        try{
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        }catch (IOException ignore){
            ignore.printStackTrace();
        }
    }

    @Test
    public void testSelectAll(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try{
            List<Country> countryList = sqlSession.selectList("selectAll");
            
        }finally {
            //关闭sqlsession
            sqlSession.close();
        }
    }
    
    private void printCountryList(List<Country> countryList){
        for (Country country : countryList) {
            System.out.printf("%-4d%4s%4s\n", country.getId(),country.getCountryname(),country.getCountrycode());
        }
    }
}

运行demo

     运行结果如下:

最终搭好的项目结构

         

遇到的问题

        创建项目时idea会自动在pom中添加版本为3.8.1版本的junit引用,发现使用注解不管用,如@Before和@Test,最终发现junit3.x是基于继承的,junit4.x是基于注解的,在junit3.x的版本不支持注解,如果想要使用junit3.x实现测试需要让测试类继承TestCase ,详情可参考博客:http://maxpin.iteye.com/blog/1184494

相关推荐
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页