MyBatis笔记(二) 最简单的insert命令

  接上一篇随笔。这里没有用到MyBatis最关键的映射器接口,因此只做个简单的insert操作,update和delete同理,就不再赘述了。

  直接上代码:

  首先是dao包下的UserDAO.java文件:

package com.alleymeowy.dao;

import com.alleymeowy.bean.User;
import com.alleymeowy.util.DBUtil;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.util.List;

public class UserDAO {

    /**
     * 根据id查询一条记录
     * @param id
     * @throws IOException
     */
    public static User selectOne(int id) throws IOException {

        SqlSession sqlSession = null;
        User user;
        try {
            sqlSession = DBUtil.getSqlSession();
            user = sqlSession.selectOne("com.alleymeowy.config.sql.Users.selectOne", id);
        } finally {
            sqlSession.close();
        }
        return user;

    }

    /**
     * 查询多条记录
     * @throws IOException
     */
    public static List<User> selectAll() throws IOException {

        SqlSession sqlSession = null;
        List<User> users;
        try {
            sqlSession = DBUtil.getSqlSession();
            users = sqlSession.selectList("com.alleymeowy.config.sql.Users.selectAll");
        } finally {
            sqlSession.close();
        }
        return users;

    }

    public static void insert(User user) throws IOException {

        SqlSession sqlSession = null;
        try {

            sqlSession = DBUtil.getSqlSession();
            int affectrows = sqlSession.insert("com.alleymeowy.config.sql.Users.insertUser", user);
            System.out.println("affectrows : " + affectrows);
            sqlSession.commit();

        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }
    
    public static void main(String[] args) throws IOException {

//        System.out.println(selectOne(1));
//        System.out.println("************");
//        System.out.println(selectAll());

        insert(new User(6, "insertPerson", 100));

    }
}

  这里添加了一个insert方法。

  然后是Users.xml文件,这里存放sql语句。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.alleymeowy.config.sql.Users">

  <select id="selectOne" parameterType="int" resultType="com.alleymeowy.bean.User">
    select id, name, age from user where id = #{id}
  </select>

  <select id="selectAll" resultType="com.alleymeowy.bean.User">
    select id, name, age from user
  </select>

  <insert id="insertUser" parameterType="com.alleymeowy.bean.User">
    insert into user(id, name, age) values(#{id}, #{name}, #{age})
  </insert>

</mapper>

  同样也是增加了一条insert语句【很简单吧】。

  其他代码如总配置文件,DBUtil工具类等都不需要改动了,这里贴出最后的输出结果:

  

  affectrows为1,改变了数据库中的1行。

  完毕。

原文地址:https://www.cnblogs.com/AlleyMeowy/p/10217318.html