我是靠谱客的博主 神勇柜子,这篇文章主要介绍MyBatis在SSM中的用法,现在分享给大家,希望可以做个参考。

概述

这篇文章记录一下如何在Web程序中使用MyBatis,其中包括pom如何引入(我这里用maven管理依赖),如何写Mapper的映射文件,以及最后对结果的处理。
这里先树下mybatis的官方中文文档。

MyBatis在Web中的应用步骤

pom.xml中如何引用

复制代码
1
2
3
4
5
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>x.x.x</version> </dependency>

其中要和Spring整合的话,需要加上下面的依赖

复制代码
1
2
3
4
5
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>x.x.x</version> </dependency>

在pom中引用完之后,还需要配置数据库的IP,端口等信息,注入到sqlSessionFactory中。

DAO层如何写接口

DAO层专门负责和数据库的处理,对于使用mybatis的增删改查来说,在dao层只需要写接口就行了,接口的实现全部交给下面要说的Mapper中去实现。

Mapper映射如何写

1.select

复制代码
1
2
3
<select id="selectPerson" parameterType="int" resultType="hashmap"> SELECT * FROM table WHERE ID = #{id} </select>

2.insert

复制代码
1
2
3
4
<insert id="insertAuthor"> insert into Author (id,username,password,email,bio) values (#{id},#{username},#{password},#{email},#{bio}) </insert>

3.update

复制代码
1
2
3
4
5
6
7
8
<update id="updateAuthor"> update Author set username = #{username}, password = #{password}, email = #{email}, bio = #{bio} where id = #{id} </update>

4.delete

复制代码
1
2
3
<delete id="deleteAuthor"> delete from Author where id = #{id} </delete>

其实mybatis的配置项很多,但是我觉得20%的常用配置项都可以完成日常工作中80%的工作了,了解官方具体说明,点击官网用法详解

查询的结果如何处理

当写好DAO,写好Mapper映射之后,只需要调用DAO中定义的接口,mybatis便会执行SQL语句,去查询并将结果返回。

总结

mybatis主要在于Mapper可以灵活的写SQL语句。同时,在web中使用mybatis时,主要过程就是几步了。

最后

以上就是神勇柜子最近收集整理的关于MyBatis在SSM中的用法的全部内容,更多相关MyBatis在SSM中内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(77)

评论列表共有 0 条评论

立即
投稿
返回
顶部