mybatis基本操作入门

1.Maven下注入依赖

2.创建核心配置文件(xml)

mybatis-config.xml中配置数据库驱动,数据库位置,账户,密码等信息

3.创建实体类

根据数据库字段创建实体类,实体类字段名使用驼峰命名,如果存在数据库字段和实体类字段命名差异,可以使用配置转换数据库字段为实体类字段。驼峰命名转换

4.创建Mapper映射文件(将实体类和数据表进行映射)

XXXMapper.xml

<mapper namespace="XXX">
 无参数
    <!-- id:sql语句的名称 -->
    <!-- resultType:查询的数据通过什么类型来保存-->
    <select id="selectAll" resultType="com.ou0618.XXX">
      select * from t_goods order by goods_id desc limit 10
    </select>

单参数

<!-- 通过Id来查找商品信息 -->
<select id="findOne" parameterType="Integer" resultType="com.lx.entity.Goods">
    select * from t_goods where goods_id = #{id}
</select>

多参数

扫描二维码关注公众号,回复: 12658702 查看本文章

<select id="findSome" parameterType="java.util.Map" resultType="com.lx.entity.Goods">
   select * from t_goods
   where
   current_price between #{MIX} and #{MAX}
   order by current_price
   limit 0,#{limit}
</select>
 

多表联查

<!-- 多表联查 -->
<select id="selectGoodsMap" resultType="java.util.LinkedHashMap">
    select g.*, c.category_name from t_goods as g, t_category as c
    where g.category_id = c.category_id
</select>

</mapper>

在Mybatis-config.xml中加载GoodsMapper.xml文件

5.初始化SessionFactory

JdbcUtil工具类创建SqlSessionFactory


public class JdbcUtil {
    private static SqlSessionFactory sqlSessionFactory = null;
 
    static {
        // 获得mybatis-config.xml
        Reader reader = null;
        // 获得会话工厂对象
        try{
            reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e){
            e.printStackTrace();
        }
    }
 
 
    // 获得SqlSession会话对象
    private static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
 
    // 关闭SqlSession会话对象
    private static void getClose(SqlSession sqlSession){
        if(sqlSession!=null){
            sqlSession.close();
        }
    }
}

6.利用SqlSession对象操作数据(增删改查)

SqlSession sqlSession = JdbcUtil.getSqlSession();
        List<Goods> goodsList = sqlSession.selectList("goods.selectAll");
        for (Goods u:
             goodsList) {
            System.out.println(u);
        }


https://blog.csdn.net/WildestDeram/article/details/99699812?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase

猜你喜欢

转载自blog.csdn.net/whb008/article/details/107503786