码迷,mamicode.com
首页 > 其他好文 > 详细

Mybatis使用之简单的增删改查

时间:2015-05-18 22:57:29      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:mybatis   mybatis增删改查   mybatis select   mybatis update   mybatis delete   

Mybatis使用之简单的增删改查

 

一:简介

     

        主要记录最简单的数据的增删改查、下一章会有各个操作详细一点的配置说明。以Author表为例(见上一博客)、Author表没有关联任何其他表、也没有特殊字段。

 

二:映射规则

 

       2.1、映射文件中的sql方法与对应的XxxMapper接口中的方法映射规则:

 

              a)映射文件的namespace的值是XxxMapper接口的全限定名、即包名+接口名称

              b)映射文件中表示增删改查的标签(select、insert、delete、update)的id的值是接口中方法名(id具有唯一性)

              c)映射文件中增删改查标签的表示参数的属性指定的值对应接口中方法的参数类型

              d)映射文件中增删改查标签的表示返回值的属性指定的值对应接口中方法的参数类型

 

       2.2、举例说明:

 

              现在需要根据一个int型的id来查询一个作者的具体信息。

              a)AuthorMapper中定义此方法

<span style="color:#FF0000;">package org.alien.mybatis.samples.mapper;</span>

public interface AuthorMapper {

    Author <span style="color:#FF0000;">getAuthorById</span>(int id);
}

              b)AuthorMapper.xml中关联此方法

<pre name="code" class="html"><span style="color:#FF0000;"><mapper namespace="org.alien.mybatis.samples.mapper.AuthorMapper"></span>
    <select id="<span style="color:#FF0000;">getAuthorById</span>" parameterMap="int" resultType="author">
        SELECT
            t.id,
            t.username,
            t.password,
            t.email,
            t.bio,
            t.favourite_section favouriteSection
        FROM author t
        WHERE t.id=#{id}
    </select>


              c)执行方法(见下文)

 

三:增删改查实现

     

       3.1、流程图:

     

              3.1.1 开发流程图(顺序可不同)

技术分享

              3.1.2 执行UML序列图

 技术分享

       3.2、具体实现过程:

     

              3.2.1、mybatis配置文件配置

 

              详细信息见上一篇、这里重点对一下两点进行说明

              a)自动扫描指定包下面所有JavaBean、并将其类名首字母小写作为key来代表当前JavaBean、用于映射文件配置增删改查标签时入参或者返回值类型是此JavaBean类型的结果集的时候。比如Author。当根据id查询某一个具体的Author的信息的时候、select标签的resultType的值就可以直接使用author来代替Author全路径名。入参同样。具体配置片段:

    <typeAliases>

        <!--That is domain.blog.Author will be registered as author. If the @Alias annotation is found its value will be
            used as an alias.@Alias("author")-->
        <package name="org.alien.mybatis.samples.model"/>
    </typeAliases>

              b)自动 扫描指定包下面所有的映射文件、并加载到内存中。这样配置的好处就是不用为每一个映射文件都要配置一次。具体配置片段:

 

    <mappers>
        <package name="org.alien.mybatis.samples.mapper"/>
    </mappers>

              3.2.2、AuthorMapper.xml映射文件配置

              a)添加

              通过insert标签定义

              b)查询

              通过select标签定义

              c)修改

              通过update标签定义

              d)删除

              通过delete标签定义

<mapper namespace="org.alien.mybatis.samples.mapper.AuthorMapper">
    <select id="getAuthorById" parameterMap="int" resultType="author">
        SELECT
            t.id,
            t.username,
            t.password,
            t.email,
            t.bio,
            t.favourite_section favouriteSection
        FROM author t
        WHERE t.id=#{id}
    </select>

    <insert id="addAuthor" parameterType="author">
        INSERT INTO author(id, username) VALUES (#{id}, #{username})
        <selectKey keyProperty="id" resultType="int">
            SELECT max(id) FROM author
        </selectKey>
    </insert>

    <delete id="deleteAuthor" parameterType="int">
        DELETE FROM author
        WHERE id = #{id}
    </delete>

    <update id="updateAuthor" parameterType="author">
        UPDATE author
        SET username = #{username}
    </update>

    <select id="getAllAuthors" resultType="author">
        SELECT
            t.id,
            t.username,
            t.password,
            t.email,
            t.bio,
            t.favourite_section favouriteSection
        FROM author t
    </select>

    <select id="getAllAuthorsCount" resultType="int">
        SELECT count(1)
        FROM author
    </select>
</mapper>

              3.2.3、编写AuthorMapper接口以及方法

 

package org.alien.mybatis.samples.mapper;

import org.alien.mybatis.samples.model.Author;

import java.util.List;

public interface AuthorMapper {

    int addAuthor(Author author);

    int deleteAuthor(int id);

    int updateAuthor(Author author);

    List<Author> getAllAuthors();

    int getAllAuthorsCount();

    Author getAuthorById(int id);
}

              3.2.4 加载配置文件、调用AuthorMapper方法

 

package org.alien.mybatis.samples.service.impl;

import org.alien.mybatis.samples.mapper.AuthorMapper;
import org.alien.mybatis.samples.model.Author;
import org.alien.mybatis.samples.service.AuthorService;
import org.alien.mybatis.samples.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * Created by andychen on 2015/5/18.<br>
 * Version 1.0-SNAPSHOT<br>
 */
public class AuthorServiceImpl implements AuthorService {

    /**
     * Add author info.
     *
     * @param author author instance
     * @return The key of current record in database.
     */
    @Override
    public int addAuthor(Author author) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            AuthorMapper authorMapper = sqlSession.getMapper(AuthorMapper.class);
            int authorId = authorMapper.addAuthor(author);
            sqlSession.commit();
            return authorId;
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    /**
     * Delete author info by author's id.
     *
     * @param authorId author id
     * @return int The number of rows affected by the delete.
     */
    @Override
    public int deleteAuthor(int authorId) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            AuthorMapper authorMapper = sqlSession.getMapper(AuthorMapper.class);
            int result = authorMapper.deleteAuthor(authorId);
            sqlSession.commit();
            return result;
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    /**
     * update author info
     *
     * @param author Author instance
     * @return int The number of rows affected by the update.
     */
    @Override
    public int updateAuthor(Author author) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            AuthorMapper authorMapper = sqlSession.getMapper(AuthorMapper.class);
            int result = authorMapper.updateAuthor(author);
            sqlSession.commit();
            return result;
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    /**
     * Query all authors
     *
     * @return all authors
     */
    @Override
    public List<Author> getAllAuthors() {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            AuthorMapper authorMapper = sqlSession.getMapper(AuthorMapper.class);
            return authorMapper.getAllAuthors();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    /**
     * Query all authors count
     *
     * @return all authors count
     */
    @Override
    public int getAllAuthorsCount() {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            AuthorMapper authorMapper = sqlSession.getMapper(AuthorMapper.class);
            return authorMapper.getAllAuthorsCount();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    @Override
    public Author getAuthorById(int id) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            AuthorMapper authorMapper = sqlSession.getMapper(AuthorMapper.class);
            return authorMapper.getAuthorById(id);
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }
}

四:补充


        更多内容:Mybatis 目录

        github地址:https://github.com/andyChenHuaYing/scattered-items/tree/master/items-mybatis

        源码下载地址:http://download.csdn.net/detail/chenghuaying/8713311

        MybatisUtil:见上一篇博客

Mybatis使用之简单的增删改查

标签:mybatis   mybatis增删改查   mybatis select   mybatis update   mybatis delete   

原文地址:http://blog.csdn.net/crave_shy/article/details/45829357

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!