mybatis实现增删改查

时间:2022-04-17 05:14:25

根据上一篇的内容为基础,在login实体类中建立有参构造方法,dao层接口内容如下:

package com.zs.dao;

import com.zs.entity.Login;

import java.util.List;

/**
 * 创建登录的接口
 */
public interface LoginDao {
    /**
     * 查询根据id查询用户信息
     */
    Login getById(int id);

    /**
     * 添加用户
     */
    int insertLogin(Login login);

    /**
     * 修改用户信息
     */
    int updateLogin(Login login);

    /**
     * 删除信息
     */
    int deleteLoginById(int id);

    /**
     * 查询所有用户信息
     */
    List<Login> getAllLogin();

}

login.xml内容如下:

<!DOCTYPE mapper PUBLIC "-//mybatis.org// Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zs.dao.LoginDao">
    <!--通过id获取信息-->
    <select id="getById" resultType="com.zs.entity.Login">
        select * from login where id=#{id}
    </select>
    <!--添加用户-->
    <insert id="insertLogin" parameterType="com.zs.entity.Login" >
        insert into login values(#{id},#{username},#{password});
    </insert>
    <!--修改用户信息-->
    <update id="updateLogin" parameterType="com.zs.entity.Login">
        update login set username=#{username},password=#{password} where id=#{id};
    </update>
    <!--删除用户信息-->
    <delete id="deleteLoginById" parameterType="Integer" >
        delete from login where id=#{id};
    </delete>
    <!--查询所有用户信息-->
    <select id="getAllLogin" resultType="com.zs.entity.Login">
        select * from login;
    </select>
</mapper>

测试类:

import com.zs.dao.LoginDao;
import com.zs.entity.Login;
import com.zs.util.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class loginTest {
    private SqlSession session =SqlSessionUtil.getSession();
    private LoginDao mapper=session.getMapper(LoginDao.class);

    @Test
    public void add(){
        Login login = new Login(7, "zhangsan", "123456");
        int i = mapper.insertLogin(login);
        // 增删改一定要提交事物,不然显示成功,但是数据库并不会添加数据
        session.commit();
        session.close();
        System.out.println(i);
    }
    @Test
    public void upd(){
        Login login=new Login(7,"xiaoming","456789");
        int i = mapper.updateLogin(login);
        session.commit();
        session.close();
        System.out.println(i);
    }

    @Test
    public void del(){
        int i = mapper.deleteLoginById(7);
        session.commit();
        session.close();
        System.out.println(i);
    }

    @Test
    public void getAll(){
        List<Login> listlogin = mapper.getAllLogin();
        session.close();
        for (Login login : listlogin) {
            System.out.println(login);
        }
    }

}