MyBatis数据查询步骤
- 创建实体类(Entity)
- 创建Mapper XML
- 编写
<select>
SQL标签 - 开启驼峰命名映射
- 新增
<mapper>
- SqlSession执行select语句
创建实体类
根据数据库表中的字段创建实体类
创建Mapper XML
在resources目录下创建mappers(映射器,保存xml文件)
创建goods.xml用于声明对象和表的映射关系,增加xml声明和mybatis dtd
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
创建对应的select标签
<!--namespace="" 命名空间,用来帮助mybatis识别调用的是否为指定位置的sql语句-->
<mapper namespace="goods">
<select id="selectAll" resultType="com.imooc.mybatis.entity.Goods">
select * from t_goods order by goods_id desc limit 10;
</select>
</mapper>
创建完这个good.xml,让maven项目加载这个文件,要在mybatis-config.xml中增加一个mappers标签,把这个good.xml加载进去。
<mappers>
<mapper resource="mappers/goods.xml"/>
</mappers>
开启驼峰命名映射
需要在mybatis-config.xml最上方中新增一个settings标签,主要用于驼峰命名转换,保证字段名称一致
<settings>
<setting name = "mapUnderscoreTocamelCase" value = "true"/>
</settings>
用SqlSession调用good.xml里的sql语句
@Test
public void testSelectAll() throws Exception {
SqlSession sqlSession = null;
try{
sqlSession = MyBatisUtils.openSession();
List<Goods> list = sqlSession.selectList("goods.selectAll");
for(Goods g : list){
System.out.println(g.getTitle());
}
}catch (Exception e){
throw e;
}finally {
MyBatisUtils.closeSqlSession(sqlSession);
}
}