学习目标:
1、mybatis的基本的操作
学习过程:
如果上一节课没有问题,那么mybatis的开发环境就已经搭建好了,由此可知,mybatis不仅仅是一个对象映射,同时还可以映射sql语句,还可以做一个参数映射,mybatis还是需要写原始的sql语句的。下面我们就把增删改查等基本功能都完成了。
1、修改映射文件GoodsMapper.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.pojo.Goods">
<!-- 定义对象映射结果 -->
<resultMap type="Goods" id="goodsMap">
<id property="goodsId" column="goods_id" />
<result property="goodsName" column="goods_name" />
<result property="goodsCash" column="goods_cash" />
<result property="goodsDesc" column="goods_desc" />
</resultMap>
<!-- sql映射 parameterType 参数类型 resultType结果类型 写原始sql语言 -->
<select id="selectGoods" parameterType="int" resultMap="goodsMap">
select *
from goods where goods_id=#{id}
</select>
<select id="selectALlGoods" resultMap="goodsMap">
select * from goods
</select>
<insert id="addGoods" parameterType="Goods" flushCache="true">
insert
into goods(goods_name,goods_desc,goods_cash)
values(#{goodsName},#{goodsDesc},#{goodsCash})
</insert>
<delete id="delGoods" parameterType="int" flushCache="true">
delete from
goods where goods_id=#{id}
</delete>
<update id="updateGoods" parameterType="Goods" flushCache="true">
update goods set
goods_name=#{goodsName},goods_desc=#{goodsDesc},goods_cash=#{goodsCash}
where goods_id=#{goodsId}
</update>
</mapper>
2、修改GoodsDao文件
public Goods getGoodsById(int id) {
SqlSession session = MyBacticUtil.getSqlSessionFactory().openSession();
//
Goods goods = session.selectOne("selectGoods", id);
session.close();
return goods;
}
public List<Goods> getAllGoods() {
SqlSession session = MyBacticUtil.getSqlSessionFactory().openSession();
List<Goods> goodses = session.selectList("selectALlGoods");
session.close();
return goodses;
}
public int addGoods(Goods goods) {
SqlSession session = MyBacticUtil.getSqlSessionFactory().openSession();
int reuslt = session.insert("addGoods", goods);
session.commit();
session.close();
return reuslt;
}
public int delGoods(int id) {
SqlSession session = MyBacticUtil.getSqlSessionFactory().openSession();
int reuslt = session.delete("delGoods", id);
session.commit();
session.close();
return reuslt;
}
public int updateGoods(Goods goods) {
SqlSession session = MyBacticUtil.getSqlSessionFactory().openSession();
int reuslt = session.update("updateGoods", goods);
session.commit();
session.close();
return reuslt;
}