以最简单的地区表为例
1.插入数据
insert into tb_area (area_name, priority) values('东苑', 1),('南苑', 7),('北苑', 5);
select * from tb_area;
2.创建接口
src/main/java/com.csj2018.o2o.dao/AreaDao.java
package com.csj2018.o2o.dao;
import com.csj2018.o2o.entity.Area;
import java.util.List;
public interface AreaDao {
/**
* 列出区域列表
* @return areaList
*/
List<Area> queryArea();
}
3. 创建mapper文件
src/main/resources/mapper/AreaDao.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.csj2018.o2o.dao.AreaDao">
<select id="queryArea" resultType="com.csj2018.o2o.entity.Area" >
select * from tb_area order by priority desc;
</select>
</mapper>
4. 创建基类BaseTest.java
package com.csj2018.o2o;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* 配置spring和junit整合,junit启动式加载springIOC容器
*/
@RunWith(SpringJUnit4ClassRunner.class)
//告诉junit spring配置文件的位置
@ContextConfiguration({"classpath:spring/spring-dao.xml"})
public class BaseTest {
}
5. 创建测试类
package com.csj2018.o2o.dao;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.csj2018.o2o.BaseTest;
import com.csj2018.o2o.entity.Area;
public class AreaDaoTest extends BaseTest{
@Autowired
private AreaDao areaDao;
@Test
public void testQueryArea() {
List<Area> areaList = areaDao.queryArea();
assertEquals(3, areaList.size());
}
}
运行测试类 Run As -> JUnit Test
执行成功,说明已经成功连接数据库