Java + MyBatis + MySql测试

Wesley13
• 阅读 690

先来看结构图

Java + MyBatis + MySql测试

包引用
mybatis-3.3.1.jar
mysql-connector-java-5.1.38-bin.jar

Mybatis配置

mybatis-config.xml

<environments default="development">
    <environment id="development">
        <transactionManager type="JDBC" />
        <!-- connecting to Local MySql -->
        <dataSource type="POOLED">
            <property name="driver" value="com.mysql.jdbc.Driver" />
            <property name="url" value="jdbc:mysql://localhost:3306/yh\_blog?charset=utf-8" />
            <property name="username" value="root" />
            <property name="password" value="root" />
        </dataSource>
    </environment>
</environments>
<mappers>
    <mapper resource="com/yehun/mapper/TestMapper.xml" />
</mappers>

MyBatisConnectionFactory.java

package com.yehun.mybatis;

import java.io.FileNotFoundException; import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisConnectionFactory {

private static SqlSessionFactory sqlSessionFactory;

static {
    try {
        String resource = "mybatis-config.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        if (sqlSessionFactory == null) {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        }
    }
    catch (FileNotFoundException fileNotFoundException) {
        fileNotFoundException.printStackTrace();
    }
    catch (IOException iOException) {
        iOException.printStackTrace();
    }
}


public static SqlSessionFactory getSqlSessionFactory() {
    return sqlSessionFactory;
}

}

TestEntity.java

package com.yehun.entity;

public class TestEntity {

public TestEntity() { }
public TestEntity(String name) { 
    this.Name = name;
}

public TestEntity(int id, String name) {
    this.Id = id;
    this.Name = name;
}

private int Id;
private String Name;
public int getId() {
    return Id;
}
public void setId(int id) {
    Id = id;
}
public String getName() {
    return Name;
}
public void setName(String name) {
    Name = name;
}

}

TestMapper.java

package com.yehun.mapper;

import java.util.List;

import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory;

import com.yehun.entity.TestEntity;

public class TestMapper {

private SqlSessionFactory sqlSessionFactory = null;

public TestMapper(SqlSessionFactory sqlSessionFactory) {
    this.sqlSessionFactory = sqlSessionFactory;
}

public List<TestEntity> getListAll() {
    List<TestEntity> list = null;
    SqlSession session = sqlSessionFactory.openSession();
    try {
        list = session.selectList("TestMapper.getListAll");
    } finally {
        session.close();
    }
    return list;
}

public TestEntity getTest(int id) {
    TestEntity entity = null;
    SqlSession session = sqlSessionFactory.openSession();
    try {
        entity = session.selectOne("TestMapper.getTest", id);
    } catch (Exception e) {
        session.close();
    }
    return entity;
}

public int insertAll(TestEntity entity) {
    int row = 0;
    SqlSession session = sqlSessionFactory.openSession();
    try {
        row = session.insert("TestMapper.insert", entity); //故意模拟了一个错误, name字段不允许重复, 插入两次自然会报错
        row = session.insert("TestMapper.insert", entity);
        session.commit();
    } catch (Exception e) {
        session.rollback();
        session.close();
        row = 0;
    }
    return row;
}

public int insert(TestEntity entity) {
    int row = 0;
    SqlSession session = sqlSessionFactory.openSession();
    try {
        row = session.insert("TestMapper.insert", entity);
        session.commit();
    } catch (Exception e) {
        session.close();
    }
    return row;
}

public int update(TestEntity entity) {
    int row = 0;
    SqlSession session = sqlSessionFactory.openSession();
    try {
        row = session.update("TestMapper.update", entity);
        session.commit();
    } catch (Exception e) {
        session.close();
    }
    return row;
}

public int delete(int id) {
    int row = 0;
    SqlSession session = sqlSessionFactory.openSession();
    try {
        row = session.delete("TestMapper.delete", id);
        session.commit();
    } catch (Exception e) {
        session.close();
    }
    return row;
}

}

TestMapper.xml

<resultMap id="result" type="TestEntity">
    <result property="id" column="Id" />
    <result property="name" column="Name" />   
</resultMap>

<select id="getListAll" resultMap="result">
    SELECT \* FROM test;
</select>

<select id="getTest" parameterType="int" resultMap="result">
    SELECT \* FROM test where id=#{id};
</select>

<insert id="insert" parameterType="TestEntity">
    insert into test(name) value(#{Name})
</insert>

<update id="update" parameterType="TestEntity">
    update test set name=#{name} where id=#{id}
</update>

<delete id="delete" parameterType="int">
    delete from test where id=#{id}
</delete>

Main.java

package com.yehun.main;

import java.util.List;

import com.yehun.entity.TestEntity; import com.yehun.mapper.TestMapper; import com.yehun.mybatis.MyBatisConnectionFactory;

public class Main {

public static void main(String\[\] args) {
    TestMapper mapper = new TestMapper(MyBatisConnectionFactory.getSqlSessionFactory());
    int row = 0;
    logger("事务--------------------");
    row = mapper.insertAll(new TestEntity("FFF")); //故意模拟了一个错误
    logger("结果: " + row);
    logger("添加--------------------");
    row = mapper.insert(new TestEntity("EEE"));
    logger("结果: " + row);
    logger("修改--------------------");
    row = mapper.update(new TestEntity(1, "BBB"));
    logger("结果: " + row);
    logger("删除--------------------");
    row = mapper.delete(15);
    logger("结果: " + row);
    logger("------------------------");
    
    
    List<TestEntity> list = mapper.getListAll();
    if(list != null) {
        logger("查询列表-----------------");
        for (TestEntity entity : list) {
            logger("Id:\\t" + entity.getId());
            logger("Name:\\t" + entity.getName());
        }
        logger("------------------------");
    }
    
    logger("查询单条-----------------");
    TestEntity entity = mapper.getTest(8);
    if(entity != null) {
        logger("Id:\\t" + entity.getId());
        logger("Name:\\t" + entity.getName());
    } else {
        logger("null");
    }
    logger("------------------------");
}

public static void logger(Object object) {
    System.out.println(object);
}

}

//结果

事务--------------------
结果: 0
添加--------------------
结果: 0
修改--------------------
结果: 1
删除--------------------
结果: 0
------------------------
查询列表-----------------
Id: 16
Name: AAA
Id: 1
Name: BBB
Id: 19
Name: EEE
Id: 8
Name: test2
------------------------
查询单条-----------------
Id: 8
Name: test2
------------------------

Demo打包下载:http://share.weiyun.com/aa6215cc1b16baf156b72d1ef658724d (密码:V25S)

如分享过期,请评论通知博主,会在看到的第一时间更新链接

点赞
收藏
评论区
推荐文章
待兔 待兔
3个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Easter79 Easter79
3年前
svg图片转字符
1.进入 https://icomoon.io官网。2.点击按钮!(https://static.oschina.net/uploads/space/2017/1228/151443_BUtm_3040505.png)3.点击添加svg图片!(https://static.oschina.net/uploads/space/2017
Wesley13 Wesley13
3年前
java——20171121
!(http://a.51jsoft.com/uploads/default/original/1X/c542896b094a42a5653fb75adf6cdacd6e35d12e.png)!(https://static.oschina.net/uploads/space/2017/1121/210719_G80Z_3715033.png)
Stella981 Stella981
3年前
RedHat6安装git
1.通过yum安装git:         一、 先配置yum:          把redhat系统镜像加载到电脑光驱中(无光驱可用u盘),然后把该镜像配置到环境变量中        !(https://static.oschina.net/uploads/space/2017/0402/133025_syOd_3276682.pn
Wesley13 Wesley13
3年前
MySQL输入密码后闪退的解决方法
控制面板系统和安全管理工具服务mysql 开启!(https://static.oschina.net/uploads/space/2017/0423/191155_biFl_3285916.png)!(https://static.oschina.net/uploads
Stella981 Stella981
3年前
DevOps系列——公司Docker测试,打版,发布实战
1\.公司服务器结构图和发布流程介绍!(https://static.oschina.net/uploads/space/2017/0507/090547_t6Bu_1416844.png)2\.node工具镜像的制作有些东西在服务器上下载比较费劲,所有我们可
Wesley13 Wesley13
3年前
7月_C++_3
!(https://static.oschina.net/uploads/space/2017/0731/100449_Mgyw_3244697.png)!(https://static.oschina.net/uploads/space/2017/0731/100659_FzL9_3244697.png)!(https://static
Stella981 Stella981
3年前
MapReduce
                                  分而治之!(https://static.oschina.net/uploads/space/2017/0417/104504_gz45_3253987.png)!(https://static.oschina.net/uploads/space/2017/0417/104
Wesley13 Wesley13
3年前
JDK 1.8.0_144 集合框架之HashMap
!(https://static.oschina.net/uploads/space/2017/0807/111713_2SnR_2447963.png)1: Node的设计 静态内部类,该类是能够被继承的。!(https://static.oschina.net/uploads/space/2017/0807/111846_POJR
Wesley13 Wesley13
3年前
JDK1.8新特性之类工厂、迭代循环应用
1创建实体类Person!(https://static.oschina.net/uploads/space/2017/1220/095547_B682_2313055.png)2创建工厂接口PersonFactory!(https://static.oschina.net/uploads/space/2017/1220/095711