Mybatis使用之简单的增删改查

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 [email protected]("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:见上一篇博客

时间: 2024-08-03 09:58:38

Mybatis使用之简单的增删改查的相关文章

MyBatis学习--简单的增删改查

jdbc程序 在学习MyBatis的时候先简单了解下JDBC编程的方式,我们以一个简单的查询为例,使用JDBC编程,如下: 1 Public static void main(String[] args) { 2 Connection connection = null; 3 PreparedStatement preparedStatement = null; 4 ResultSet resultSet = null; 5 6 try { 7 //加载数据库驱动 8 Class.forName

MyBatis3.2.2+SpringMVC3.0 简单实现(增删改查,Web版实现)

MyBatis3.2.2+SpringMVC3.0 简单实现(增删改查,Web版实现) 首先,需要知道Eclipse如何创建Dynamic Web Project for Maven,我们首先需要知道如何用Eclipse创建动态部署的Maven Web-app 项目.参考以下链接的博客:http://blog.csdn.net/smilevt/article/details/8215558. 构建完之后:实现具体的增删改查,不去部署Web war的时候我们用Junit单元测试CRUD功能.代码如

EF5(6) 简单三层 增删改查

1:项目结构 2:每层添加对其他层的引用,这里我们把除了Web层之外的所有的层生成的文件都放到解决方案下的Library文件夹下,然后每个项目分别来引用里面的dll项目文件. 我们在Model项目上,右键属性->生成-> 在下面的输出里面,选择上一级的 Library文件夹 2.2 我们调整项目的生成顺序 ,在解决方案或者是任意项目上右键,选择 生成依赖项,调整各个项目的依赖,这样的目的就是调整项目的生成顺序. 注意,这里你选择依赖项,并没有给项目与项目之间增加了dll的引用,只是单纯的修改了

通过JDBC进行简单的增删改查

通过JDBC进行简单的增删改查(以MySQL为例) 目录 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操作 (1)定义记录的类(可选) (2)连接的获取 (3)insert (4)update (5)select (6)delete 四.测试 五.代码分析 六.思考问题 前言:什么是JDBC 维基百科的简介: Java 数据库连接,(Java Database Connectivity,简称JDBC)

用CI框架向数据库中实现简单的增删改查

以下代码基于CodeIgniter_2.1.3版 用PHP向数据库中实现简单的增删改查(纯代码)请戳 http://www.cnblogs.com/corvoh/p/4641476.html CodeIgniter_2.1.3与PHP5.6的兼容问题请戳 http://www.cnblogs.com/corvoh/p/4649357.html 增: //insert//语法:$bool=$this->db->insert('表名',关联数组); $data=array( 'username'=

用PHP向数据库中实现简单的增删改查(纯代码,待完善)

<?php $con = mysql_connect("localhost:3306","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("test", $con); $result = mysql_query("SELECT * FROM user"); echo "

entity framework—简单的增删改查

应用程序对数据库执行CRUD时,通过entity framework方式,实际上是对DbContext的操作,DbContext是EF的入口,DbContext拿到对应的消息(CRUD)后,通过ORM中的Mapping来将对象O映射成数据库中的关系R. 下面就简单的实现一下利用entity framework实现简单的增删改查.首先要说明的是我已经建立了在解决方案中映射了数据库中表"Customer".所有的操作都是针对这张表. 1.增加 Customer customer = new

通过JDBC进行简单的增删改查(以MySQL为例) 目录

通过JDBC进行简单的增删改查(以MySQL为例) 目录 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操作 (1)定义记录的类(可选) (2)连接的获取 (3)insert (4)update (5)select (6)delete 四.测试 五.代码分析 六.思考问题 前言:什么是JDBC 维基百科的简介: Java 数据库连接,(Java Database Connectivity,简称JDBC)

JDBC实现最简单的增删改查

好久没写博客了,今天刚进入一家公司实习,在实习这段期间想把自己所学的东西通过博客记录下来 今天上午简单回顾了一下用JDBC实现最简单的增删改查 废话不多说,接下来就说明怎么用JDBC实现最简单的增删改查 我用的数据库是Mysql 1.创建一个MAVEN项目,需要导入两个jar包 分别为lombok 和 mysql 的jar包,在MAVEN的仓库网站可以轻松找得到 2.导入jar包之后 我们来进行数据库的连接操作 其步骤为 第一步:加载数据库驱动 Class.forName("com.mysql.