MyBatis在SSM中的用法

来源:互联网 发布:mac 移动硬盘 ntfs 编辑:程序博客网 时间:2024/06/01 16:01

概述

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

MyBatis在Web中的应用步骤

pom.xml中如何引用

<dependency>  <groupId>org.mybatis</groupId>  <artifactId>mybatis</artifactId>  <version>x.x.x</version></dependency>

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

<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

<select id="selectPerson" parameterType="int" resultType="hashmap">  SELECT * FROM table WHERE ID = #{id}</select>

2.insert

<insert id="insertAuthor">  insert into Author (id,username,password,email,bio)  values (#{id},#{username},#{password},#{email},#{bio})</insert>

3.update

<update id="updateAuthor">  update Author set    username = #{username},    password = #{password},    email = #{email},    bio = #{bio}  where id = #{id}</update>

4.delete

<delete id="deleteAuthor">  delete from Author where id = #{id}</delete>

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

查询的结果如何处理

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

总结

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

原创粉丝点击