006. MyBatis基本使用---03MyBatis数据查询
原创
©著作权归作者所有:来自51CTO博客作者上岸很慢的原创作品,请联系作者获取转载授权,否则将追究法律责任
1.MyBatis数据查询步骤
1.1 创建实体类entity
1.2 创建mapper xml文件来说明当前sql语句是什么并编写
1.3 在mybatis-config.xml开启驼峰映射
1.4 在mybatis-config.xml新增mapper xml的声明
1.5 SqlSession执行select语句
2.具体实现操作
2.1 创建entity包用来存放实体类
package com.imooc.mybatis.entity;
public class Category {
private Integer categoryId;
private String categoryName;
private Integer parentId;
private Integer categoryLevel;
private Integer categoryOrder;
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public Integer getCategoryLevel() {
return categoryLevel;
}
public void setCategoryLevel(Integer categoryLevel) {
this.categoryLevel = categoryLevel;
}
public Integer getCategoryOrder() {
return categoryOrder;
}
public void setCategoryOrder(Integer categoryOrder) {
this.categoryOrder = categoryOrder;
}
}
2.2 在resource目录下创建新的子目录mappers(映射器)存放xml文件,创建goods.xml,用来说明实体类和哪一个表对应
resultType代表将sql语句返回的结果包装成对应的goods对象
<?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="goods">
<select id="selectAll" resultType="com.imooc.mybatis.entity.Goods" >
select * from t_goods order by goods_id desc limit 10
</select>
2.3 在mybatis-config.xml开启驼峰命名转换
<settings>
<!-- goods_id ==> goodsId 驼峰命名转换 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
2.4 在mybatis-config.xml声明mapper的配置文件
<!--声明mapper的配置文件-->
<mappers>
<mapper resource="mappers/goods.xml"/>
</mappers>
2.5 测试,查询常用方法selectOne() 、selectList()
/**
* select查询语句执行
*/
@Test
public void testSelectAll() throws Exception
{
SqlSession session = null;
try
{
session = MyBatisUtils.openSession();
List<Goods> list = session.selectList("goods.selectAll");//goods.selectAll 命名空间.(SQL语句的ID)
for (Goods g : list)
{
System.out.println(g.getTitle());
}
}
catch (Exception e)
{
throw e;
}
finally
{
MyBatisUtils.closeSession(session);
}
}