框架:Mybatis+mysql入门使用

一、简介

  MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。

二、入门使用

  1、添加依赖

          a、使用maven管理依赖,以我本次使用的版本为例

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.3</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
    </dependencies>
View Code

         b、也可以使用gradle管理依赖

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile 'org.mybatis:mybatis:3.2.3'
    compile 'mysql:mysql-connector-java:5.1.38'
}
View Code

        c、也可以去官网下载,官网地址:http://www.mybatis.org/mybatis-3/

      2、初始化数据库和初始数据,以数据库moy_mybatis和表t_test为例

## 创建数据库
CREATE DATABASE    moy_mybatis;
## 创建一个测试表
CREATE TABLE t_test(
    id INT(11) AUTO_INCREMENT,
    create_time DATE COMMENT '创建时间',
    modify_time DATE COMMENT '修改时间',
    content VARCHAR (50) COMMENT '内容',
    PRIMARY KEY (id)
);
View Code

     3、新建实体类TestEntity

package com.moy.mybatis3.entity;

import java.util.Date;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/20  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
public class TestEntity {
    private Integer id;
    private Date createTime;
    private Date modifyTime;
    private String content;

    public Integer getId() {
        return id;
    }

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

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getModifyTime() {
        return modifyTime;
    }

    public void setModifyTime(Date modifyTime) {
        this.modifyTime = modifyTime;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "TestEntity{" +
                "id=" + id +
                ", createTime=" + createTime +
                ", modifyTime=" + modifyTime +
                ", content='" + content + '\'' +
                '}';
    }
}
View Code

     4、新建接口TestMapper

package com.moy.mybatis3.mapper;

import com.moy.mybatis3.entity.TestEntity;

import java.io.Serializable;
import java.util.List;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/20  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
public interface TestMapper {

    List<TestEntity> list();

    TestEntity get(Serializable id);

    int insert(TestEntity TestEntity);

    int update(TestEntity TestEntity);

    int delete(Serializable id);

    int count();
}
View Code

     5、新建实体映射文件Test.xml,这里的namespace就是写TestMapper全类名,否则不能使用动态代理的方式调用接口TestMapper

<?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="com.moy.mybatis3.mapper.TestMapper">
    <select id="list" resultType="TestEntity">
        SELECT * FROM t_test
    </select>

    <select id="count" resultType="int">
        SELECT count(*) FROM t_test
    </select>

    <select id="get" parameterType="int" resultType="TestEntity">
        SELECT id,create_time as createTime,modify_time as modifyTime ,content
         FROM t_test WHERE id=#{id}
    </select>

    <insert id="insert" parameterType="TestEntity">
        INSERT INTO t_test (create_time,modify_time,content)
        VALUES (#{createTime},#{modifyTime},#{content})
    </insert>

    <update id="update" parameterType="TestEntity">
        UPDATE t_test SET modify_time=#{modifyTime},content=#{content}
        WHERE id = #{id}
    </update>

    <delete id="delete" parameterType="int">
        DELETE FROM t_test WHERE id = #{id}
    </delete>
</mapper>
View Code

     6、新建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>
    <typeAliases>
        <!--项目实体类对应的包名-->
        <package name="com.moy.mybatis3.entity"/>
    </typeAliases>
        <!--myql数据库连接信息-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/moy_mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123"/>
            </dataSource>
        </environment>
    </environments>
    <!--配置实体映射xml路径-->
    <mappers>
        <mapper resource="mapper/Test.xml"></mapper>
    </mappers>
</configuration>    
View Code

     7、为了方便测试,编写一个获取SqlSession的工具类Mybatis3Utils

package com.moy.mybatis3.utils;

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.Reader;
import java.util.Objects;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/19  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
public abstract class Mybatis3Utils {

    public static final SqlSessionFactory sqlSessionFactory;
    public static final ThreadLocal<SqlSession> sessionThread = new ThreadLocal<>();

    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static SqlSession getCurrentSqlSession() {
        SqlSession sqlSession = sessionThread.get();
        if (Objects.isNull(sqlSession)) {
            sqlSession = sqlSessionFactory.openSession();
            sessionThread.set(sqlSession);
        }
        return sqlSession;
    }

    public static void closeCurrentSession() {
        SqlSession sqlSession = sessionThread.get();
        if (Objects.nonNull(sqlSession)) {
            sqlSession.close();
        }
        sessionThread.set(null);
    }
}
View Code

     8、新建测试类TestMapperTest测试

package com.moy.mybatis3.mapper;

import com.moy.mybatis3.entity.TestEntity;
import com.moy.mybatis3.utils.Mybatis3Utils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static org.junit.Assert.*;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/20  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
public class TestMapperTest {

    SqlSession sqlSession;
    TestMapper testMapper;

    @Before
    public void before() {
        sqlSession = Mybatis3Utils.getCurrentSqlSession();
        testMapper = sqlSession.getMapper(TestMapper.class);
    }

    @After
    public void after() {
        Mybatis3Utils.closeCurrentSession();
    }

    @Test
    public void insert() {
        TestEntity entity = new TestEntity();
        entity.setCreateTime(new Date());
        entity.setModifyTime(new Date());
        entity.setContent("我是内容");
        System.out.println(testMapper.insert(entity));
        sqlSession.commit();
    }

    @Test
    public void count() {
        System.out.println(testMapper.count());
    }

    @Test
    public void list() {
        List<TestEntity> list = testMapper.list();
        System.out.println(Arrays.toString(list.toArray()));
    }

    @Test
    public void get() {
        System.out.println(testMapper.get(1));
    }

    @Test
    public void update() {
        TestEntity entity = new TestEntity();
        entity.setId(1);
        entity.setModifyTime(new Date());
        entity.setContent("我是修改后内容");
        testMapper.update(entity);
        sqlSession.commit();
    }

    @Test
    public void delete() {
        testMapper.delete(1);
        sqlSession.commit();
    }
}
View Code

 

yexiangyang

moyyexy@gmail.com


 

 

posted @ 2018-02-20 15:26  墨阳  阅读(7143)  评论(0编辑  收藏  举报