Mybatis的应用

1. 定义

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

参考文档: MyBatis 快速入门和重点详解_mokingone的博客-优快云博客

2. 使用Mybatis

2.1 pom文件导入(maven)

         maven仓库传送门:https://link.youkuaiyun.com/?target=https%3A%2F%2Fmvnrepository.com%2F

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

 2.1.2 从官方获取:https://link.youkuaiyun.com/?target=https%3A%2F%2Fmybatis.org%2Fmybatis-3%2Fzh%2Findex.html

2.2 配置插件

  <plugins>
      <plugin interceptor="com.junli.mybatis.demo.mybatis.JunliPlugin"/>
  </plugins>

2.3 mapper映射

 <mappers>
    <mapper resource="xml/TestMapper.xml"/>
    <mapper resource="xml/PostsMapper.xml"/>
</mappers>

2.3.1 方式一:mapper下resource绑定

<!-- 每一个Mapper.XML都需要在Mybatis核心配置文件中注册!-->
<mappers>
   <mapper resource="com.sxt.UserMapper.xml"></mapper>
</mappers>

2.3.2 方式二:mapper下class绑定(同名同包)

<mappers>
  <mapper class="com.sxt.pojo.Exam"></mapper>
</mappers>

2.4 mapper映射的增删改查

    // 增
    <insert id="addExam" useGeneratedKeys="true" keyProperty="eid">
        insert into exam (eid,pname,cno,userid,classid,singlenumber,
        singlecore,examdate,examtime,testtime)
        values (default,#{pname},#{cno},#{userid},#{classid},#{singlenumber},
                #{singlecore},#{examdate},#{examtime},#{testtime})
    </insert>

    // 删
    <delete id="delExam">
        delete  from exam where eid=#{eid}
    </delete>

    // 改
    <update id="updExam">
        update exam set pname=#{pname},
                        cno=#{cno},
                        userid=#{userid},
                        classid=#{classid},
                        singlenumber=#{singlenumber},
                        singlecore=#{singlecore},
                        examdate=#{examdate},
                        examtime=#{examtime},
                        testtime=#{testtime}
                    where eid=#{eid}
    </update>

    // 查
    <select id="getAllExam" resultType="com.sxt.pojo.Exam">
        select * from exam
    </select>

3. 分析错误

  • 标签不要匹配错误
  • 程序配置文件必须符合规范
  • NullPointerException,没有注册到资源
  • 输出的xml文件中存在中文乱码问题
  • maven资源没有导出问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值