• MyBatis(二)最简易的增、删、改、查


    这篇是承接上一篇的helloWorld程序。首先将一系列初始化的步骤再做一个工厂类进行包装,代码如下:

    package com.tinaluo.sun;
    
    import java.io.InputStream;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.*;
    
    public class FKSqlSessionFactory {
        private static SqlSessionFactory sqlSessionFactory=null;
        static{
            try
            {
                InputStream inputStream=Resources.getResourceAsStream("mybatis-config.xml");
                sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);    
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
        public static SqlSession getSqlSession()
        {
            return sqlSessionFactory.openSession();
        }
        public static SqlSessionFactory getSqlSessionFactory()
        {
            return sqlSessionFactory;
        }
    }

    UserMapper.xml文件修改后:

    <?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="org.fkit.mapper.UserMapper">
        <!-- 增加 -->
        <insert id="saveUser" parameterType="com.tinaluo.sun.User"
            useGeneratedKeys="true">
            insert into tb_user(name,sex,age)
            values(#{name},#{sex},#{age})
        </insert>
        <!-- 查找 -->
        <select id="selectUser" parameterType="int" resultType="com.tinaluo.sun.User">
            select *
            from tb_user where id=#{id}
        </select>
        <!-- 更新 -->
        <update id="modifyUser" parameterType="com.tinaluo.sun.User">
            update tb_user set
            name=#{name},sex=#{sex},age=#{age} where id=#{id}
        </update>
        <!-- 删除 -->
        <delete id="removeUser" parameterType="int">
            delete from tb_user where
            id=#{id}
        </delete>
    </mapper>

    目录结构如下:

  • 相关阅读:
    linux基本命令之grep
    Linux在线练习网站
    MySql分表分库思路
    SqlServer触发器
    SqlServer存储过程
    Spring常用注解总结
    SpringMVC的HelloWorld
    XML基础和Web基本概念(JavaWeb片段一)
    红黑树-结点的删除(C语言实现)
    红黑树-结点的插入
  • 原文地址:https://www.cnblogs.com/tinaluo/p/8388233.html
Copyright © 2020-2023  润新知