MyBatis快速入门

1 建立数据库和表

1.1 创建mybatis名称的数据库

1.2 建立测试表

-- 创建客户表
CREATE TABLE t_customer(
   id INT PRIMARY KEY AUTO_INCREMENT,
   NAME VARCHAR(20),
   gender CHAR(1),
   telephone VARCHAR(20)
);

插入一些测试数据

2 创建项目、导入依赖

2.1 IDEA中创建Java项目

2.2 导入MyBatis依赖

<?xml version="1.0" encoding="UTF-8"?>
<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>com.yiidian</groupId>
    <artifactId>ch01_01_mybatis_hello</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <!-- mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
</project>

3 编写SqlMapConfig.xml配置

在resources目录建立名称为:SqlMapConfig.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>

    <!-- 1.数据库连接信息-->
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="jdbc"></transactionManager>
            <dataSource type="pooled">
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEcndoing=utf8"/>
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    

</configuration>

4 编写Pojo实体

package com.yiidian.domain;

/**
 * 实体类
 * 一点教程网 - www.yiidian.com
 */
public class Customer {
    private Integer id;
    private String name;
    private String gender;
    private String telephone;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", telephone='" + telephone + '\'' +
                '}';
    }
}

5 编写Dao接口及映射文件

5.1 编写Dao接口

package com.yiidian.dao;
import com.yiidian.domain.Customer;
import java.util.List;
/**
 * Dao接口
 *一点教程网 - www.yiidian.com
 */
public interface CustomerDao {
    /**
     * 查询所有用户
     */
    public List<Customer> findAll();
}

5.2 编写Dao映射文件

和Dao接口在同一个目录下,建立同名的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">
<!--
   namespace: 用于指定该映射文件需要映射的Dao接口
-->
<mapper namespace="com.yiidian.dao.CustomerDao">

    <!-- 为findAll方法映射SQL语句 -->
    <!--
       id: 需要映射的方法名称
       resultType: 返回值需要封装的对象类型
           注意:如果是集合类型,只需要指定集合中的存放元素类型即可
     -->
    <select id="findAll" resultType="com.yiidian.domain.Customer">
        select * from t_customer
    </select>


</mapper>

6 关联Dao映射文件

在之前的SqlMapConfig.xml关联Dao映射文件

具体内容如下:

<!--2.关联Dao映射文件-->
<mappers>
   <mapper resource="com/yiidian/dao/CustomerDao.xml"/>
</mappers>

7 编写测试类

package com.yiidian.mybatis;

import com.yiidian.dao.CustomerDao;
import com.yiidian.domain.Customer;
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;
import java.util.List;

/**
 * MyBatis测试类
 * 一点教程网 - www.yiidian.com
 */
public class TestCustomerDao {

    public static void main(String[] args) throws Exception {
        //1.加载SqlMapConfig.xml
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");

        //2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);

        //3.创建SqlSession
        SqlSession sqlSession = factory.openSession();

        //4.生成Dao接口代理对象
        CustomerDao userDao = sqlSession.getMapper(CustomerDao.class);

        //5.执行Dao接口方法
        List<Customer> list = userDao.findAll();
        for(Customer c:list){
            System.out.println(c);
        }

        //6.释放资源
        sqlSession.close();
        in.close();
    }
}

8 配置log4j.properties

把log4j.properties日志配置拷贝到resources目录下

内容如下:

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=debug, stdout

9 运行测试

运行测试类的main方法,执行结果如下:

 

源码下载:https://pan.baidu.com/s/1zq2GIwzOHl7aNKwgM87LQA

热门文章

优秀文章