文档章节

Java + MyBatis + MySql测试

yehun
 yehun
发布于 2017/03/30 18:02
字数 734
阅读 604
收藏 0

先来看结构图

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

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>
		<typeAlias alias="TestEntity" type="com.yehun.entity.TestEntity" />
	</typeAliases>

	<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>
</configuration>


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

<?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="TestMapper">

    <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>

</mapper>

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)

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

© 著作权归作者所有

yehun
粉丝 8
博文 218
码字总数 137315
作品 0
长宁
高级程序员
私信 提问
Spring Boot 整合 MyBatis

最近项目原因可能会继续开始使用MyBatis,已经习惯于spring-data的风格,再回头看xml的映射配置总觉得不是特别舒服,接口定义与映射离散在不同文件中,使得阅读起来并不是特别方便。 Spring...

中关村的老男孩
06/24
92
0
MyBatis的初步使用(入门操作)

MyBatis是一个基于Java的开源的持久层框架 首先进行MyBatis的环境搭建 1.下载MyBatis 下载地址https://github.com/mybatis/mybatis-3/releases 2.将MyBatis相关的包导入到工程中 将下载好的M...

IT-Mamba
2015/08/17
128
1
MyBatis Generator 配置文件自动生成

官网:http://mybatis.github.io/generator/index.html 项目目录结构 添加Maven插件(pom.xml) 配置Maven执行命令 配置MyBatis GeneratorXML generatorConfig.xml init.properties 执行运行......

MLeo
2015/10/28
626
0
springboot系列十三 mybatis 注解和xml2种方式

依赖 使用方式 注解和xml 注解方式 配置 mapper接口 mapper扫描配置 在启动类中添加注解 测试接口 xml方式 配置 启动类mapper扫描 mapper接口和xml配置 测试接口 源码地址 https://gitee.co...

yimingkeji
2018/12/14
352
0
Mybatis 学习笔记二 与spring搭配

Mybatis 学习笔记二 与spring搭配 maven依赖 配置 mybatis配置 conf.xml 注意:保持基本配置即可; spring配置 applicationContext.xml mapper配置 userMapper.xml meng.mybatis.test.UserM...

晨猫
2018/11/16
20
0

没有更多内容

加载失败,请刷新页面

加载更多

PostgreSQL 11.3 locking

rudi
今天
5
0
Mybatis Plus sql注入器

一、继承AbstractMethod /** * @author beth * @data 2019-10-23 20:39 */public class DeleteAllMethod extends AbstractMethod { @Override public MappedStatement injectMap......

一个yuanbeth
今天
10
1
一次写shell脚本的经历记录——特殊字符惹的祸

本文首发于微信公众号“我的小碗汤”,扫码文末二维码即可关注,欢迎一起交流! redis在容器化的过程中,涉及到纵向扩pod实例cpu、内存以及redis实例的maxmemory值,statefulset管理的pod需要...

码农实战
今天
4
0
为什么阿里巴巴Java开发手册中不建议在循环体中使用+进行字符串拼接?

之前在阅读《阿里巴巴Java开发手册》时,发现有一条是关于循环体中字符串拼接的建议,具体内容如下: 那么我们首先来用例子来看看在循环体中用 + 或者用 StringBuilder 进行字符串拼接的效率...

武培轩
今天
8
0
队列-链式(c/c++实现)

队列是在线性表功能稍作修改形成的,在生活中排队是不能插队的吧,先排队先得到对待,慢来得排在最后面,这样来就形成了”先进先出“的队列。作用就是通过伟大的程序员来实现算法解决现实生活...

白客C
今天
81
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部