MyBatis数据查询步骤
第一创建实体类
package com.imooc.mybatis.entity; public class GoodsEntity { private Integer goodsId; //商品编号 private String title;//标题 private String subTitle;//子标题 private Float originalCost;//原价 private Float currentPrice;//折扣价格 private Float discount;// 折扣 private Integer isFreeDelivery;//是否包邮 1-包邮 0-不包邮 private Integer categoryId;// 分类编号 public Integer getGoodsId() { return goodsId; } public void setGoodsId(Integer goodsId) { this.goodsId = goodsId; } public String getTilte() { return title; } public void setTilte(String tilte) { this.title = tilte; } public String getSubTitle() { return subTitle; } public void setSubTitle(String subTitle) { this.subTitle = subTitle; } public Float getOriginalCost() { return originalCost; } public void setOriginalCost(Float originalCost) { this.originalCost = originalCost; } public Float getCurrentPrice() { return currentPrice; } public void setCurrentPrice(Float currentPrice) { this.currentPrice = currentPrice; } public Float getDiscount() { return discount; } public void setDiscount(Float discount) { this.discount = discount; } public Integer getIsFreeDelivery() { return isFreeDelivery; } public void setIsFreeDelivery(Integer isFreeDelivery) { this.isFreeDelivery = isFreeDelivery; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } }
第二部 创建Mapper MXL
<?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标签
<mapper namespace="goods"> <!--根据namespace 加上 id 精确找寻sql语句 --> <!--resultType结果类型 goods对象类型 --> <select id="findAll" resultType="com.imooc.mybatis.entity.GoodsEntity"> <!-- 编写sql语句 --> SELECT * FROM t_goods ORDER BY goods_id DESC limit 10; </select> </mapper>
开启驼峰命名法
在mybatis-config。xml里配置
<!-- 引入外部properties文件 --> <properties resource="datasource.properties"/> <settings> <!--设置启用数据库字段下划线映射到java对象的驼峰式命名属性,默认为false--> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings>
第五步 新增mapper
<mappers> <!-- 映射goods。xml --> <mapper resource="mappers/goods.xml"></mapper> </mappers> 在mybatis-config.xml配置
第六步执行sql
package com.imooc.mybatis.test; import com.imooc.mybatis.entity.GoodsEntity; import com.imooc.mybatis.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.sql.Connection; import java.util.List; public class SelectTestor { @Test public void selectAll() throws Exception { //调用MybatisUtils工具类获得数据库连接 SqlSession sqlSession = null; try { //获取sql对象 sqlSession = MybatisUtils.openSession(); //执行sql List<GoodsEntity> list = sqlSession.selectList("goods.findAll"); //查看连接状态 Connection conn = MybatisUtils.getConnection(sqlSession); for (int i = 0; i < list.size(); i++) { GoodsEntity goodsEntity = list.get(i); System.out.println(goodsEntity.getTilte()+"---"+goodsEntity.getDiscount()); } }catch (Exception e){ throw e; }finally { MybatisUtils.release(sqlSession); } } }