1. 程式人生 > >Mybatis+mysql入門使用

Mybatis+mysql入門使用

初始 man 路徑 typealias 信息 depend evel foxmail aso

一、簡介

  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]:[email protected]  <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]:[email protected]  <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

技術分享圖片
<?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]:[email protected]  <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]:[email protected]  <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

[email protected]


Mybatis+mysql入門使用