上一节通过mybatis-generator自动生成了CategoryMapper接口,pojo等类,接下来我们写几个简单的测试来进行调用。

一、添加依赖

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>

二、测试SqlSessionFactroy

首先我们看下怎样实例化sqlSessionFactory,然后获取CategoryMapper。

1.新建文件resources/properties/config.property,用来保存数据库连接串和账号。

data_source_url=jdbc:mysql://localhost:3306/store
data_source_username=root
data_source_password=root

2.在resources/spring目录新建spring的配置文件applicationContext.xml

3.配置数据连接。 在applicationContext.xml中添加bean节点dataSource,详细配置参考:http://www.oschina.net/p/druid

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${data_source_url}"/>
<property name="username" value="${data_source_username}"/>
<property name="password" value="${data_source_password}"/>
<!-- 初始化连接大小 -->
<property name="initialSize" value="1"/>
<!-- 初始化连接池最大使用连接数量 -->
<property name="maxActive" value="20"/>
<!-- 初始化连接池最小空闲 -->
<property name="minIdle" value="1"/>
<!-- 获取连接最大等待时间,单位毫秒-->
<property name="maxWait" value="60000"/>
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000"/>
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<!--如果用Oracle,则把poolPreparedStatements配置为true,mysql可以配置为false。分库分表较多的数据库,建议配置为false。-->
<property name="poolPreparedStatements" value="false"/>
<property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>
<property name="validationQuery" value="SELECT 1"/>
<property name="testWhileIdle" value="true"/>
<property name="testOnBorrow" value="false"/>
<property name="testOnReturn" value="false"/>
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="true"/>
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="1800"/>
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true"/>
</bean>

4.然后配置bean sqlSessionFactory和sqlSession。

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.data.pojo"/>
<property name="mapperLocations" value="classpath*:mapper/CategoryMapper.xml"></property>
<property name="configLocation" value="classpath:config/mybatis-config.xml"></property>
</bean>

4.测试

有了上面的配置,就可以直接以注解的方式实例化SqlSessionFactory.

@ContextConfiguration(locations = "classpath:spring/applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class SqlSessionTests {
@Autowired
private SqlSession sqlSession; @Test
public void testSqlSession(){
CategoryMapper categoryMapper= sqlSession.getMapper(CategoryMapper.class);
Category category= categoryMapper.selectByPrimaryKey(1);
if(category==null){
System.out.println("Do not exist");
}
else{
System.out.println(category.getName());
}
}
}

三、测试直接实例化CategoryMapper

更加简洁的方式是直接通过注解实例化CategoryMapper

1.在applicationContext.xml新增bean节点

<!-- scan for mappers and let them be autowired -->
<mybatis:scan base-package="com.data.mapper"/>
<!-- mapper 接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.data.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>

2.直接给CategoryMapper添加@Resource注解,来进行实例化。

@ContextConfiguration(locations = "classpath:spring/applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class CategoryDaoTests {
@Resource
CategoryMapper categoryMapper; @Test
public void test_selectById(){
Category category=categoryMapper.selectByPrimaryKey(1);
System.out.println(category.getName());//Fish
} @Test
public void test_count(){
CategoryExample example=new CategoryExample();
long result=categoryMapper.countByExample(example);
System.out.println(result);
} @Test
public void test_insert(){
System.out.println("before insert:count "+categoryMapper.countByExample(new CategoryExample())); Category category=new Category();
category.setName("Test");
categoryMapper.insert(category); System.out.println("after insert:count "+categoryMapper.countByExample(new CategoryExample())); } @Test
public void test_delete(){
System.out.println("before insert:count "+categoryMapper.countByExample(new CategoryExample())); CategoryExample example=new CategoryExample();
example.createCriteria().andNameEqualTo("Test");
int result=categoryMapper.deleteByExample(example);
System.out.println("删除条数:"+result); System.out.println("after insert:count "+categoryMapper.countByExample(new CategoryExample())); }
}

JAVA入门[8]-测试mybatis的更多相关文章

  1. JAVA入门--目录

    在此记录自己的JAVA入门笔记,备忘 JAVA入门[1]--安装JDK JAVA入门[2]-安装Maven JAVA入门[3]—Spring依赖注入 JAVA入门[4]-IntelliJ IDEA配置 ...

  2. JAVA入门[9]-mybatis多表关联查询

    概要 本节要实现的是多表关联查询的简单demo.场景是根据id查询某商品分类信息,并展示该分类下的商品列表. 一.Mysql测试数据 新建表Category(商品分类)和Product(商品),并插入 ...

  3. Java基础-SSM之mybatis快速入门篇

    Java基础-SSM之mybatis快速入门篇 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 其实你可能会问什么是SSM,简单的说就是spring mvc + Spring + m ...

  4. java web开发入门七(mybatis)基于intellig idea

    mybatis 一. 入门开发步骤 1.导入相关jar包 mybatis3.4.2核心开发包 asm-5.1.jarcglib-3.2.4.jarcommons-logging-1.1.3.jarlo ...

  5. 测试人员学Java入门指南

    目标读者 本指南特别适合有Python基础的同学学习Java入门,对于没有任何编程经验的同学可能会存在困难. 为什么测试人员要学Java 选择Java,应该不错.TesterHome测试论坛知名大佬基 ...

  6. java入门到秃路线导航,元芳你怎么看?【教学视频+博客+书籍整理】

    目录 一.Java基础 二.关于JavaWeb基础 三.关于数据库 四.关于ssm框架 五.关于数据结构与算法 六.关于开发工具idea 七.关于项目管理工具Mawen.Git.SVN.Gradle. ...

  7. [刘阳Java]_快速搭建MyBatis环境_第2讲

    1.MyBatis的环境配置 导入MyBatis包, mybatis-3.2.8.jar 导入MySQL驱动包, mysql-connector-java-5.1.24-bin.jar 创建表的实体类 ...

  8. Java入门-浅析Java学习从入门到精通【转】

    一. JDK (Java Development Kit)  JDK是整个Java的核心,包括了Java运行环境(Java Runtime Envirnment),一堆Java工具和Java基础的类库 ...

  9. Java入门——(1)Java编程基础

    Java入门--(1)Java编程基础 第二章 Java编程基础   JAVA 代码的基本格式: 修饰符 class 类名{ 程序代码 }   2.1关键字:赋予了特殊含义的单词.   2.2标识符: ...

随机推荐

  1. 【APP问题定位(二)】Charles定位工具

    Charles工具是APP测试中简单有使用的一款测试工具,可以通过捕获request和response的信息初步确定bug的原因所在. 本文将从安装.使用两个方面来介绍. 安装 点击这里进入下载页,注 ...

  2. Anaconda快捷搭建Python2和Python3环境

    我们在使用Pycharm编辑Python程序经常会因为不熟悉Python2和Python3的一些代码区别而导致错误,我们知道他们之间很多代码是必须运行在对应版本中的,否则是会报错的.因此,本文介绍一个 ...

  3. NLP论文泛读之《教材在线评论的情感倾向性分析》

    NLP论文泛读之<教材在线评论的情感倾向性分析> 本文借助细粒度情感分类技术, 对从网络上抓取大量计算机专业本科教材的评价文本进行情感极性 分析, 从而辅助商家和出版社改进教材的质量.制定 ...

  4. C#线程调用带参数的方法

    在 .NET Framework 2.0 版中,要实现线程调用带参数的方法有两种办法.第一种:使用ParameterizedThreadStart.调用 System.Threading.Thread ...

  5. SpringAware

    哈哈,终于把分布式的课程演讲给混过去了,下面开始随便自己学点东西. 正题:SpringAware--------在实际项目中,用到spring容器的本省功能资源,这是Bean必须意识到Spring容器 ...

  6. configpraser模块

    configpraser配置文件,example.conf [data] #节点 username = Jason password = 123 [public] comment = stuff pu ...

  7. LKD: Chapter 6 Kernel Data Structures

    这一章我们研究四种主要的数据结构: linked lists, queues, maps, binary trees. Linked Lists:(<linux/list.h>) 在lin ...

  8. pyqt5实现打开子窗口

    # -*- coding: utf-8 -*- import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * class Fi ...

  9. HBuilder入门(构建h5+APP)

    if(window.plus) { plusReady(); } else { //plusready事件(自带事件)调用了才可使用h5+API document.addEventListener(& ...

  10. 5分钟搞定iOS抓包Charles,让数据一清二楚

    Charles安装 HTTP抓包 HTTPS抓包   1. Charles安装 官网下载安装Charles:https://www.charlesproxy.com/download/ 2. HTTP ...