Mybatis小记——使用mybatis完成CRUD操作

和JDBC的区别

  • 在SQL语句传参时,JDBC使用的是 当做占位符,而在MyBatis中,占位符放在XXXMapper.xml文件中,使用#{}作为占位符在#{id},#{name}中放入形参
  • 使用map集合封装参数时,#{这里放的是map中的key值}

配置文件

userMapper.xml

namespace是car

<?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">
<!--namespace命名空间,防止id重复 使用时【nameSpace.id】-->
<mapper namespace="car">
    <!--insert sql:保存⼀个人信息,id是这条SQL语句的唯一标识-->
    <insert id="insertUser">
        <!--使用集合
        mybatis的占位符不是? 是#{} 大括号中的值为 map中的key-->
        insert into t_user(id,name,age,sex) values (null,#{name},#{age},#{sex})
    </insert>
    <insert id="insertUserByPojo">
        <!--使用POJO类
        mybatis的占位符不是? 是#{} 大括号中的值为 map中的key-->
        insert into t_user(id,name,age,sex) values (null,#{name},#{age},#{sex})
    </insert>
    <delete id="deleteUserById">
        delete from t_user where id = #{id}
    </delete>
    <update id="updateUserById">
        update t_user set age=#{age} where id= #{id}
    </update>
    <select id="selectUserById" resultType="POJO.User">
        <!--列名与POJO类中字段名不一致时,不一致的字段赋不上值,在查询时使用as为列名起别名-->
        select id,name,age,sex from t_user where id = #{id}
    </select>
    <select id="selectAllUser" resultType="POJO.User">
        select id,name,age,sex from t_user
    </select>
</mapper>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--开启mybatis标准日志-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/p_mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="hyp"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>

        <!--sql映射⽂件创建好之后,需要将该⽂件路径配置到这⾥-->
        <!--执行XXXMapper.xml文件的路径,-->
        <!--resource属性会自动从类的根目录下开始查找资源,
        而XXMapper.xml文件刚好在resource目录下,所以不用在这里加任何东西 -->
        <mapper resource="userMapper.xml"/>
        <mapper resource="testNameSpace.xml"/>
    </mappers>
</configuration>

工具类

在使用mybatis实现CRUD操作前,先创建一个工具类,这个工具类可以直接获取SqlSession对象。减少代码冗余

insert

insert有两种方式,一种不使用Pojo类,逐个传入参数。需要用到Map集合,将要传入的参数封装到集合中,然后将这个集合对象传入insert方法中

<mapper namespace="car">
    <!--insert sql:保存⼀个人信息,id是这条SQL语句的唯一标识-->
    <insert id="insertUser">
        <!--使用集合
        mybatis的占位符不是? 是#{} 大括号中的值为 map中的key-->
        insert into t_user(id,name,age,sex) values (null,#{name},#{age},#{sex})
    </insert>
</mapper>
 @Test
    public void testInsertUserByMap() {
        //使用map集合传递参数
        //前端传过来的数据封装到一个map集合中
        Map<String, Object> map = new HashMap<>();
        map.put("name", "张三");
        map.put("age", 20);
        map.put("sex", "男");

        SqlSession sqlSession = MybatisUtils.getSqlSession();

        int count = sqlSession.insert("car.insertUser", map);
        System.out.println(count + "行收到影响");
        sqlSession.commit();
        sqlSession.close();
    }
  • 第二种,使用pojo传参
    **注意:**使用pojo类进行传参时,pojo中一定要有gerXXX()方法,XXX一定要和Mapper.xml文件中的占位符符号相同。因为mybatis使用pojo类传参的底层是调用pojo的getXXX方法
<mapper namespace="car">
	 <insert id="insertUserByPojo">
        <!--使用POJO类
        mybatis的占位符不是? 是#{} 大括号中的值为 map中的key-->
        insert into t_user(id,name,age,sex) values (null,#{name},#{age},#{sex})
    </insert>
</mapper>
 @Test
    public void testInsertUserByPojo() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //使用pojo类 传递参数
        int count = sqlSession.insert("insertUserByPojo", new User(null, "大树", 21, "男"));
        System.out.println(count + "行收到影响");
        sqlSession.commit();
        sqlSession.close();
    }

delete

<mapper namespace = "car">
  <delete id="deleteUserById">
  <!--sql语句-->
        delete from t_user where id = #{id}
    </delete>
</mapper>
    public void testDeleteUserId() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        int count = sqlSession.delete("deleteUserById", 4);
        System.out.println(count + "行受到影响");
        sqlSession.commit();
        sqlSession.close();
    }

update

<mapper namespace = "car">
	<update id="updateUserById">
        update t_user set age=#{age} where id= #{id}
    </update>
</mapper>
 @Test
    public void testUpdateUserById() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        Map<String, Object> map = new HashMap<>();
        map.put("age", 100);
        map.put("id", 8);
        sqlSession.update("updateUserById", map);
        sqlSession.commit();
        sqlSession.close();
    }

也可以使用pojo类进行传参

select

根据条件获取
步骤:

  1. 先是用工具类获取sqlSession对象
  2. 使用sqlSession对象来调用相关方法
  3. 进行事务提交
 @Test
    public void testSelectAllUser() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        List<Object> allUser = sqlSession.selectList("car.selectAllUser");
        sqlSession.commit();
        sqlSession.close();
        allUser.forEach(user -> System.out.println(user));
    }

结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值