1.还是要新建Shop.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.dao.ShopInforDao"> </mapper>
2.将它引入mybatis配置文件:
<mappers> <mapper resource="mapper/ShopMapper.xml"/> <!-- <package name="com.dao"/> --> </mappers>
3.新建dao代码ShopDao(一般放在dao包下):
import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.One; import org.apache.ibatis.annotations.Options; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import org.apache.ibatis.mapping.FetchType; import com.po.Shop; //基于注解模式的配置方式 public interface ShopDao { //查询单个商品信息 @Select("select * from shop where id = #{id}") @Results({ @Result(id=true, column="id", property="id"), @Result(column="name", property="name"), @Result(column="information", property="information"), @Result(column="sum", property="sum"), @Result(column="price", property="price") }) Shop SelectShopById(Integer id); //查询所有商品 @Select("select * from shop") List<Shop> SelectShopAll(); //插入单个商品 @Insert("insert into shop(name,information,sum,price) values(#{name},#{information},#{sum},#{price})") @Options(useGeneratedKeys=true,keyProperty="id") int saveShop(Shop shop); //删除单个商品 @Delete("delete from shop where id = #{id}") void DeleteShopById(Integer id); //更新商品信息 @Update("update shop set name=#{name},information=#{information},sum=#{sum},price=#{price} where id = #{id}") void UpdateShopById(Shop shop); //一对一查询 @Select("select * from shop where id = #{id}") @Results({ @Result(id=true, column="id", property="id"), @Result(column="name", property="name"), @Result(column="information", property="information"), @Result(column="price", property="price"), @Result(column="id", property="shopInfor", //id为传过去的参数,shopInfor为shop表中属性 one=@One( select="yh.mapper.ShopInforDao.SelectShopInforByShopId", fetchType=FetchType.EAGER)) //立即加载 }) Shop OneToOneSelectShopAndShop_inforById(Integer id); }
4.使用MybatisUtil工具类测试。
public class ShopTest { //查询单个商品 @Test public void TestSelectShopById() throws IOException{ SqlSession session=MybatisUntil.openSession(); ShopDao shopDao=session.getMapper(ShopDao.class); Shop shop=shopDao.SelectShopById(19); System.out.println(shop); session.close(); } }
5.测试结果: