MyBatis的删除、修改、插入操作!!!

发布时间:2023年12月19日

准备工作:1.创建一个maven工程,然后将pojo类导入到项目中去。

?????????????????? 2.导入依赖到pom.xml文件中

?????????????????? 3.在resources中创建log4j.properites和mybatis-config.xml

?????????????????? 4.创建UserMapper接口和UserMapper.xml文件

1.创建Maven工程,还没有配置Maven的和还不会的去看这里啦:maven的下载安装与配置环境变量!!!(全网最详细)-CSDN博客

User.java:???? (pojo类)

/*
 * Copyright (c) 2020, 2023,  All rights reserved.
 *
 */
package com.by.pojo;

import java.io.Serializable;
import java.util.Date;

/**
 * <p>Project: mybatis - User</p>
 * <p>Powered by scl On 2023-12-18 11:38:09</p>
 * <p>描述:<p>
 *
 * @author 孙臣龙 [1846080280@qq.com]
 * @version 1.0
 * @since 17
 */
public class User implements Serializable {
    private Integer id;
    private String username;
    private String password;
    private Date birthday;
    private String sex;
    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}


2.导入依赖到pom.xml文件中

<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>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
    <build>
        <!-- 如果不添加此节点src/main/java目录下的所有配置文件都会被漏掉。 -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
    </build>

???? 3.在resources中创建log4j.properites和mybatis-config.xml

log4j.properites:

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

?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>
    <!--使用dev环境-->
    <environments default="dev">
        <!--dev环境-->
        <environment id="dev">
            <transactionManager type="JDBC"></transactionManager>
            <!--使用连接池中的数据源-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3305/mybatis?characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
    <!-- 扫描映射文件 -->
    <mappers>
        <mapper resource="com/by/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

4.创建UserMapper接口和UserMapper.xml文件

UserMapper.java:

package com.by.mapper;
 
import com.by.pojo.User;
import org.apache.ibatis.annotations.Param;
 
import java.util.Map;
 
/**
 * <p>Project: mybatis - UserMapper</p>
 * <p>Powered by scl On 2023-12-19 15:24:18</p>
 * <p>描述:<p>
 *
 * @author 孙臣龙 [1846080280@qq.com]
 * @version 1.0
 * @since 17
 */
public interface UserMapper {
  
}

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.by.mapper.UserMapper">
 
</mapper>

5.创建测试类MyBatisTest

/*
 * Copyright (c) 2020, 2023,  All rights reserved.
 *
 */
package com.by;
 
import com.by.mapper.UserMapper;
import com.by.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.After;
import org.junit.Before;
import org.junit.Test;
 
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
 
 
/**
 * <p>Project: mybatis - MyBatisTest</p>
 * <p>Powered by scl On 2023-12-18 11:44:53</p>
 * <p>描述:<p>
 *
 * @author 孙臣龙 [1846080280@qq.com]
 * @version 1.0
 * @since 17
 */
public class MyBatisTest {
 
    private InputStream inputStream;
    private SqlSession sqlSession;
 
 
    @Before
    public void init() throws IOException {
        // 加载配置文件
        String resource = "mybatis-config.xml";
        inputStream = Resources.getResourceAsStream(resource);
 
        // 创建sqlSessionFActory
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 
        // 获得数据的绘画实例
        sqlSession = sessionFactory.openSession();
    }
 
   
 
    @After
    public void close() throws IOException {
        inputStream.close();
        sqlSession.close();
    }
 
}

? 准备工作完成后,开始功能的开发:

删除操作:

UserMapper.java:

package com.by.mapper;

import com.by.pojo.User;
import org.apache.ibatis.annotations.Param;

import java.util.Map;

/**
 * <p>Project: mybatis - UserMapper</p>
 * <p>Powered by scl On 2023-12-19 15:24:18</p>
 * <p>描述:<p>
 *
 * @author 孙臣龙 [1846080280@qq.com]
 * @version 1.0
 * @since 17
 */
public interface UserMapper {
   

    void deleteUserById(Integer id);


}

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.by.mapper.UserMapper">

    <delete id="deleteUserById" parameterType="java.lang.Integer" >
        delete from user where id=#{id}
    </delete>

</mapper>

测试类:

/*
 * Copyright (c) 2020, 2023,  All rights reserved.
 *
 */
package com.by;

import com.by.mapper.UserMapper;
import com.by.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.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * <p>Project: mybatis - MyBatisTest</p>
 * <p>Powered by scl On 2023-12-18 11:44:53</p>
 * <p>描述:<p>
 *
 * @author 孙臣龙 [1846080280@qq.com]
 * @version 1.0
 * @since 17
 */
public class MyBatisTest {

    private InputStream inputStream;
    private SqlSession sqlSession;


    @Before
    public void init() throws IOException {
        // 加载配置文件
        String resource = "mybatis-config.xml";
        inputStream = Resources.getResourceAsStream(resource);

        // 创建sqlSessionFActory
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        // 获得数据的绘画实例
        sqlSession = sessionFactory.openSession();
    }


    /**
     *  删除数据
     * @throws IOException
     */
    @Test
    public void deleteUserById(){
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.deleteUserById(41);
        sqlSession.commit();
    }
  

    @After
    public void close() throws IOException {
        inputStream.close();
        sqlSession.close();
    }

}

修改操作:

UserMapper.java:? (模仿前边的代码,在UserMapper.java接口中添加这个方法)

void updateUserById(User user);

UserMapper.xml:? (模仿前边的代码,在UserMapper.xml中添加这个方法)

 <update id="updateUserById" parameterType="com.by.pojo.User">
        update user set
            username=#{username},
            birthday=#{birthday}, sex=#{sex}, address=#{address}
        where id=#{id}
    </update>

在测试类中编写测试方法:(模仿前边的代码,在中添加这个方法)

/**
     *  修改数据
     * @throws IOException
     */
    @Test
    public void updateUserById(){
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = new User();
        user.setUsername("李星云");
        user.setAddress("中原");
        user.setBirthday(new Date());
        user.setPassword("123");
        user.setSex("男");
        user.setId(42);
        userMapper.updateUserById(user);
        sqlSession.commit();
    }

添加操作:

?UserMapper.java:? (模仿前边的代码,在UserMapper.java接口中添加这个方法)

    void addUser(User user);

UserMapper.xml:? (模仿前边的代码,在UserMapper.xml中添加这个方法)


    <insert id="addUser" useGeneratedKeys="true" keyProperty="id" parameterType="com.by.pojo.User">
        insert into user(username,password,birthday,sex,address)
        values(#{username},#{password},#{birthday},#{sex},#{address})
    </insert>

在测试类中编写测试方法:(模仿前边的代码,在中添加这个方法)

 /**
     *  添加数据
     * @throws IOException
     */
    @Test
    public void addUser(){
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = new User();
        user.setUsername("女帝");
        user.setAddress("齐国");
        user.setBirthday(new Date());
        user.setSex("女");
        user.setPassword("123");
        userMapper.addUser(user);
        System.out.println(user.getId());
        sqlSession.commit();
    }

?

文章来源:https://blog.csdn.net/qq_64847107/article/details/135092582
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。