小白体验:Mybatis初体验之CRUD,增删改查其实很简单

 

昨天入门了Mybatis,学习了如何去配置一个简单Mybatis项目,今天来看看怎么去增删改查吧!

项目环境:idea2020 + MySQL 8 + Maven 3.6

老样子先准备数据库的内容:

CREATE TABLE `user` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(32) NOT NULL COMMENT '用户名称',
  `birthday` DATETIME DEFAULT NULL COMMENT '生日',
  `sex` CHAR(1) DEFAULT NULL COMMENT '性别',
  `address` VARCHAR(256) DEFAULT NULL COMMENT '地址',
  PRIMARY KEY  (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;



INSERT  INTO `user`
    (`id`,`username`,`birthday`,`sex`,`address`) 
VALUES 
    (1,'张三','2018-02-27 17:47:08','男','北京'),
    (2,'李四','2018-03-02 15:09:37','女','北京金燕龙'),
    (3,'王五','2018-03-04 11:34:34','女','北京金燕龙'),
    (5,'麻子','2018-03-04 12:04:06','男','北京金燕龙'),
    (6,'老王','2018-03-07 17:37:26','男','北京'),
    (8,'名字','2018-03-08 11:44:00','女','北京修正');

1、搭建Mybatis环境,具体参考:https://blog.csdn.net/moro_s/article/details/106065918

搭建好的目录结构如下(使用XML映射文件的方式):

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>Mybatis_day02</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

    <properties>
        <!-- 文件拷贝时的编码 -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <!-- 编译时的编码 -->
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
    </properties>
</project>

2、CRUD操作:

添加数据:

在userdao接口中添加方法:

    /**
     * 添加方法
     * @param user
     */
    int saveUser(User user);

在userdao对应的xml中添加映射

<!--添加方法-->
    <insert id="saveUser" parameterType="com.moro.domain.User">
        insert into user (username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address});
    </insert>

测试类中

    private SqlSessionFactory sqlSessionFactory = null;
    private SqlSession sqlSession = null;
    private IUserDao iUserDao = null;
    private InputStream is = null;
//    初始化各类资源
    @Before
    public void init(){
        try {
            is = Resources.getResourceAsStream("SqlMapConfig.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (is != null) {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            sqlSession = sqlSessionFactory.openSession();
            iUserDao = sqlSession.getMapper(IUserDao.class);
        }
    }
//    执行完方法后释放各类资源
    @After
    public void destroy(){
        //提交事务
        sqlSession.commit();
        //师范资源
        sqlSession.close();
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    @Test
    public void testSave(){
        User user = new User("张三",new Date(),"男","重庆");
        iUserDao.saveUser(user);
    }

删除记录:

在userdao接口中添加方法:

    /**
     * 删除方法
     * @param userId
     */
    void deleteUser(Integer userId);

在userdao对应的xml中添加映射

    <!--删除方法-->
    <update id="deleteUser" parameterType="java.lang.Integer">
        delete from user where id = #{userId};
    </update>

测试类中

    private SqlSessionFactory sqlSessionFactory = null;
    private SqlSession sqlSession = null;
    private IUserDao iUserDao = null;
    private InputStream is = null;
//    初始化各类资源
    @Before
    public void init(){
        try {
            is = Resources.getResourceAsStream("SqlMapConfig.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (is != null) {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            sqlSession = sqlSessionFactory.openSession();
            iUserDao = sqlSession.getMapper(IUserDao.class);
        }
    }
//    执行完方法后释放各类资源
    @After
    public void destroy(){
        //提交事务
        sqlSession.commit();
        //师范资源
        sqlSession.close();
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }    
    @Test
    public void testDelete(){
        iUserDao.deleteUser(69);
    }

更新记录:

在userdao接口中添加方法:

    /**
     * 更新方法
     * @param user
     */
    void updateUser(User user);

在userdao对应的xml中添加映射

    <!--更新方法-->
    <update id="updateUser" parameterType="com.moro.domain.User">
        update user set username=#{username} where id=#{id};
    </update>

测试类中

    private SqlSessionFactory sqlSessionFactory = null;
    private SqlSession sqlSession = null;
    private IUserDao iUserDao = null;
    private InputStream is = null;
//    初始化各类资源
    @Before
    public void init(){
        try {
            is = Resources.getResourceAsStream("SqlMapConfig.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (is != null) {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            sqlSession = sqlSessionFactory.openSession();
            iUserDao = sqlSession.getMapper(IUserDao.class);
        }
    }
//    执行完方法后释放各类资源
    @After
    public void destroy(){
        //提交事务
        sqlSession.commit();
        //师范资源
        sqlSession.close();
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }    
    @Test
    public void testUpdate(){
        User user = new User();
        user.setId(64);
        user.setUsername("麻子");
        System.out.println(user);
        iUserDao.updateUser(user);
    }

删除记录:

在userdao接口中添加方法:

    /**
     * 删除方法
     * @param userId
     */
    void deleteUser(Integer userId);

在userdao对应的xml中添加映射

    <!--删除方法-->
    <update id="deleteUser" parameterType="java.lang.Integer">
        delete from user where id = #{userId};
    </update>

测试类中

    private SqlSessionFactory sqlSessionFactory = null;
    private SqlSession sqlSession = null;
    private IUserDao iUserDao = null;
    private InputStream is = null;
//    初始化各类资源
    @Before
    public void init(){
        try {
            is = Resources.getResourceAsStream("SqlMapConfig.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (is != null) {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            sqlSession = sqlSessionFactory.openSession();
            iUserDao = sqlSession.getMapper(IUserDao.class);
        }
    }
//    执行完方法后释放各类资源
    @After
    public void destroy(){
        //提交事务
        sqlSession.commit();
        //师范资源
        sqlSession.close();
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }     
    @Test
    public void testDelete(){
       iUserDao.deleteUser(69);
    }
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值