学MyBatis看这四篇就够了!(2)之实现增删改查

本文阅读 3 分钟
首页 代码,Java 正文

代码整体预览

dao层:

UserMapper:

package com.lwh.dao;

import com.lwh.pojo.User;

import java.util.List;

public interface UserMapper { 
    List<User> getUserList();

    //查询对应id
    User getUserById(int id);

    //插入用户
    int insertUser(User user);

    //更新用户
    int updateUser(User user);

    //删除用户
    int deleteUser(User user);
}

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="com.lwh.dao.UserMapper">
    <select id="getUserList" resultType="com.lwh.pojo.User">
        select * from user
    </select>
    <select id="getUserById" resultType="com.lwh.pojo.User" parameterType="int">
        select * from user where id=#{id}
    </select>
    <insert id="insertUser" parameterType="com.lwh.pojo.User">
        insert into user values(#{id},#{name},#{pwd})
    </insert>
    <update id="updateUser" parameterType="com.lwh.pojo.User">
        update user set name=#{name},pwd=#{pwd} where id=#{id}
    </update>
    <delete id="deleteUser" parameterType="com.lwh.pojo.User">
        delete from user where id=#{id}
    </delete>
</mapper>

pojo实体类层:

package com.lwh.pojo;

public class User { 
    private int id;
    private String name;
    private String pwd;
    public User(){ 

    }

   (为了展示明了,简洁,展示时省略tostring和get,set方法,请读者误偷懒,否则报错)
}

Utils:

MybatisUtils.java:

package com.lwh.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils { 
    private static SqlSessionFactory sqlSessionFactory;
    static { 
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try { 
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) { 
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    public static SqlSession getSqlSession(){ 
        return sqlSessionFactory.openSession();
    }
}

resources文件夹下的Mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--每一个xml都要注册-->
    <mappers>
        <mapper resource="com/lwh/dao/UserMapper.xml"/>
    </mappers>
</configuration>

test:

package com.lwh.dao;

import com.lwh.pojo.User;
import com.lwh.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserDaoImpl { 
    @Test
    /*\ 查找全部的用户 */
    public void test(){ 
        //获取连接
        SqlSession sqlSession= MybatisUtils.getSqlSession();
        //执行sql
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        //
        List<User> list=userMapper.getUserList();
        for (User user:list)
        { 
            System.out.println(user);
        }
        sqlSession.close();
    }

    /* id查询 */
    @Test
    public void test2() { 
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.getUserById(1);
        System.out.println(user);
        sqlSession.close();
    }

    /* 插入操作 */
    @Test
    public void insert(){ 
        User user=new User(4,"哈哈","1234444");
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        int judge=userMapper.insertUser(user);
        if(judge>0)
        { 
            System.out.println("插入成功!");
        }

        //一定要执行提交事务,增删改都要提交事务才能做到表的修改
        sqlSession.commit();
        sqlSession.close();
    }

    /* 更新用户 */

    @Test
    public void update(){ 
        User user=new User(4,"芜湖","12345");
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        int judge=userMapper.updateUser(user);
        if(judge>0)
        { 
            System.out.println("修改成功");
        }
        sqlSession.commit();
        sqlSession.close();
    }

    /** * 删除用户 */
    @Test
    public void delete(){ 
        User user=new User(4,"芜湖","233");
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        int judge= userMapper.deleteUser(user);
        if(judge>0)
        { 
            System.out.println("删除成功");
        }
        sqlSession.commit();
        sqlSession.close();
    }
}

img

实现增,删,改,查

增删改查操作在实现了一个的基础上,只需要修改UserMapper.xml文件和UserMapper.java接口即可!

id是接口中增加的方法名,parameterType是传递的参数类型,resultType是获取到的类型,当传递进来的是对象时,可以直接用#{对象属性}直接获取到值
    1. 首先增加UserMapper.java文件接口中方法 //查询对应id User getUserById(int id); 1. 再增加UserMapper.java文件接口中方法 <select id="getUserById" resultType="com.lwh.pojo.User" parameterType="int"> select * from user where id=#{id} </select> 1. 增加测试方法 <pre><span class="token annotation punctuation">@Testpublic</span> <span class="token keyword">void</span> <span class="token function">test2</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{ <!-- --></span> <span class="token class-name">SqlSession</span> sqlSession <span class="token operator">=</span> <span class="token class-name">MybatisUtils</span><span class="token punctuation">.</span><span class="token function">getSqlSession</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token class-name">UserMapper</span> userMapper <span class="token operator">=</span> sqlSession<span class="token punctuation">.</span><span class="token function">getMapper</span><span class="token punctuation">(</span><span class="token class-name">UserMapper</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token class-name">User</span> user <span class="token operator">=</span> userMapper<span class="token punctuation">.</span><span class="token function">getUserById</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>user<span class="token punctuation">)</span><span class="token punctuation">;</span> sqlSession<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span> </pre>

<li> 删

    6. 首先增加UserMapper.java文件中的接口方法 //删除用户 int deleteUser(User user); 7. 再增加UserMapper.xml中的语句 <delete id="deleteUser" parameterType="com.lwh.pojo.User"> delete from user where id=#{id}</delete>
  1. 增加测试方法 <pre><span class="token annotation punctuation">@Testpublic</span> <span class="token keyword">void</span> <span class="token function">delete</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{ <!-- --></span> <span class="token class-name">User</span> user<span class="token operator">=</span><span class="token keyword">new</span> <span class="token class-name">User</span><span class="token punctuation">(</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token string">"芜湖"</span><span class="token punctuation">,</span><span class="token string">"233"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token class-name">SqlSession</span> sqlSession <span class="token operator">=</span> <span class="token class-name">MybatisUtils</span><span class="token punctuation">.</span><span class="token function">getSqlSession</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token class-name">UserMapper</span> userMapper<span class="token operator">=</span>sqlSession<span class="token punctuation">.</span><span class="token function">getMapper</span><span class="token punctuation">(</span><span class="token class-name">UserMapper</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token keyword">int</span> judge<span class="token operator">=</span> userMapper<span class="token punctuation">.</span><span class="token function">deleteUser</span><span class="token punctuation">(</span>user<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token keyword">if</span><span class="token punctuation">(</span>judge<span class="token operator">></span><span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{ <!-- --></span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"删除成功"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> sqlSession<span class="token punctuation">.</span><span class="token function">commit</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> sqlSession<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span> </pre>
9. 改 ​ 同上,参见参考代码 10. 增 同上,参见参考代码 ## 注意事项 1. 增删改必须要conmmit 2. 编写properties文件解耦合(数据库版本MySQL8.22)
    2. db.properties: driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai username=root password=123456 2. 修改mybatis-config.xml文件: ​ 不仅可以连MySQL还可以连Oracle等,若要修改,不用增加删除,只需要讲environments默认修改为environment中的id对应的值,如下,连接到的时id为development的语句
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--导入properties文件-->
    <properties resource="db.properties"/>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
        <environment id="the_two">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--每一个xml都要注册-->
    <mappers>
        <mapper resource="com/lwh/dao/UserMapper.xml"/>
    </mappers>
</configuration>
  1. (了解)参数可以用map传入,若要取到值,只需要写出对应的key就可以取到value值
本文为互联网自动采集或经作者授权后发布,本文观点不代表立场,若侵权下架请联系我们删帖处理!文章出自:https://blog.csdn.net/m0_46435741/article/details/119034987
-- 展开阅读全文 --
Redis底层数据结构--跳跃表
« 上一篇 04-28
BUUCTF Web [强网杯 2019]随便注
下一篇 » 06-24

发表评论

成为第一个评论的人

热门文章

标签TAG

最近回复