MyBatis实现增删改查案例

本文介绍了如何在Java中使用MyBatis框架,包括定义User类,编写UserMapper接口,以及配置UserMapper.xml来实现增删改查操作,同时展示了数据库连接配置和mybatis-config.xml的设置。
摘要由CSDN通过智能技术生成

1.准备User类

package com.suchuanlin.pojo;

import lombok.Data;

@Data
public class User {
    private Integer id;
    private String username;
    private String password;
}

2.编写UserMapper接口

package com.suchuanlin.mapper;

import com.suchuanlin.pojo.User;
import java.util.List;

public interface UserMapper {

    int insert(User user);

    int update(User user);

    int delete(Integer id);

    User selectById(Integer id);

    List<User> selectAll();

}

3.编写UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.suchuanlin.mapper.UserMapper">

    <insert id="insert" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
        insert into user (username,password) values(#{username},#{password})
    </insert>

    <update id="update">
        update user set username = #{username}, password = #{password} where id = #{id}
    </update>

    <delete id="delete">
        delete from user where id = #{id}
    </delete>

    <select id="selectById" resultType="user">
        select * from user where id = #{id}
    </select>

    <select id="selectAll" resultType="user">
        select * from user
    </select>

</mapper>

4.准备好jdbc.properties数据库连接配置文件

jdbc.url=jdbc:mysql://localhost:3306/mybatis-example
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.username=root
jdbc.password=1234

5.编写mybatis-config配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <!--引入properties文件-->
    <properties resource="jdbc.properties"/>

    <settings>
        <!--开启mybatis的日志输出-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!--开启驼峰命名自动映射-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <typeAliases>
        <!--批量将包下的类起别名,别名为类的首字母小写-->
        <package name="com.suchuanlin.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <package name="com/suchuanlin/mapper"/>
    </mappers>

</configuration>

6.测试程序文件(注:将获取sqlSession和关闭资源的方法提取出来,减少测试代码累赘)

package com.suchuanlin.test;

import com.suchuanlin.mapper.UserMapper;
import com.suchuanlin.pojo.User;
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 org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyBatisTest {

    private SqlSession sqlSession;

    @BeforeEach  //每次走测试方法之前,先走的初始化方法
    public void before() throws IOException {
        //1.读取配置文件输入流
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        //2.创建sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //3.获取SqlSession对象
        sqlSession = sqlSessionFactory.openSession();
    }

    @AfterEach  //每次走测试方法之后,调用的关闭资源方法
    public void clean(){
        sqlSession.close();
    }

    @Test
    public void testInsert(){
        //4.获取代理mapper对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = new User();
        user.setUsername("zhangsan");
        user.setPassword("123456");
        int rows = mapper.insert(user);
        System.out.println("rows = " + rows);
        System.out.println("userId = " + user.getId());
        //5.关闭资源/提交事务
        sqlSession.commit();
    }

    @Test
    public void testUpdate(){
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = new User();
        user.setId(2);
        user.setUsername("lisi");
        user.setPassword("xxoo");
        int rows = mapper.update(user);
        System.out.println("rows = " + rows);
        sqlSession.commit();
    }

    @Test
    public void testDelete(){
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int rows = mapper.delete(5);
        System.out.println("rows = " + rows);
        sqlSession.commit();
    }

    @Test
    public void testSelectById(){
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.selectById(1);
        System.out.println(user);
    }

    @Test
    public void testSelectAll(){
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.selectAll();
        for (User user : userList) {
            System.out.println(user);
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值