Mybatis - Implementation of CRUD

Note: The transaction must be committed when adding, deleting, and modifying

code

//            提交事务
 sqlSession.commit();

1.namespace-namespace

The fully qualified name (package name + class name) in the namespace should be consistent with the fully qualified name (package name + class name) of the Dao/Mapper interface

2.select

select, query

Attributes

(1)id:

Unique identifier under the namespace, fill in the method name in the corresponding interface in the namespace

(2)resultType:

Sql statement execution return value

  • When the return value type is an object or a collection of objects: fill in the fully qualified name of the object (package name + class name)
  • When the return value is a string or an integer type, etc., fill in the corresponding type, such as String, Integer

(2)resultType:

Parameter Type

  • When the parameter type is an object or a collection of objects: fill in the fully qualified name of the object (package name + class name)
  • When the parameter is a string or integer type, etc., fill in the corresponding type, such as String, Integer

Mybatis-Add, delete, modify and check process

1. Create a mybatis tool class and fill in the following code

  • 1. Create the com.kuang.utils package
  • 2. Create the mybatis tool class MybatisUtils
  • Note the name of the Mybatis configuration file, mine is mybatis-config.xml
package com.kuang.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;

//sqlSessionFactory用来构建sqlSession
public class MybatisUtils {
    
    

    //提升SqlSessionFactory的作用域
    private static SqlSessionFactory sqlSessionFactory;

    static{
    
    
        try {
    
    
//            使用Mybatis第一步获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";//填写自己配置文件的名称
//            通过Resources读取配置文件
            InputStream inputStream = Resources.getResourceAsStream(resource);
//          通过SqlSessionFactoryBuilder加载一个流,构建一个sqlSession工厂
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (IOException e){
    
    
            e.printStackTrace();
        }
    }
//    既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
//    SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
    public static SqlSession getSqlSession(){
    
    
       return sqlSessionFactory.openSession();

    }
}

insert image description here

2. Create the Mybatis configuration file mybatis-config.xml

  • Create a new mybatis-config.xml under the resources file
  • Pay attention to modifying your own database information
  • Note that every Mapper.xml that needs to be created for the future needs to be registered in the Mybatis core configuration file
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuratio是核心配置文件-->
<configuration>
    <environments default="development">
        <environment id="development">
<!--            transactionManager:事务管理-->
            <transactionManager type="JDBC"/>
<!--            dataSource中包含数据库相关配置-->
            <dataSource type="POOLED">
<!--               driver:数据库驱动com.mysql.jdbc.Driver -->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
<!--                url:数据库连接地址
                    useSSL=false 安全连接,只有当由安全证书时才能用true
                    useUnicode=true  Unicode编码
                    characterEncoding=UTF-8   字符为UTF-8格式
                    serverTimezone=GMT    设置时区
                    &符要用转义字符&amp;
                    -->
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useEncoding=false&amp;characterEncoding=UTF-8&amp;serverTimezone=GMT"/>
<!--               username:用户名-->
                <property name="username" value="root"/>
<!--                password:数据库连接密码-->
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
<!--    每个Mapper.xml都需要在Mybatis核心配置文件中注册-->
    <mappers>
        <mapper resource="com/kuang/dao/UserMapper.xml"/>
    </mappers>

</configuration>

insert image description here

3. Create an entity class object

  • Create a new com.kuang.pojo package
  • Create a new User class with attributes corresponding to the attributes of the database user table
package com.kuang.pojo;

//实体类对象
public class User {
    
    
    private int id;
    private String name;
    private String pwd;

    public int getId() {
    
    
        return id;
    }

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

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public String getPwd() {
    
    
        return pwd;
    }

    public void setPwd(String pwd) {
    
    
        this.pwd = pwd;
    }

    @Override
    public String toString() {
    
    
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

insert image description here

4. Write the interface

  • Create com.kuang.dao package
  • Create UserDao interface
package com.kuang.dao;

import com.kuang.pojo.User;

import java.util.List;

public interface UserDao {
    
    

//    返回所有用户信息
    List<User> getUserList();

//    根据用户id查询用户信息
    User getUserById(Integer id);

//    添加一个用户
    Integer addUser(User user);

//    删除一个用户
    Integer deleteUser(Integer id);

//    修改用户信息
    Integer updateUser(User user);
}

insert image description here

5. Write the implementation class UserMapper.xml of the interface

  • Create a new UserMapper.xml file under the com.kuang.dao package
  • Note that the namespace should correspond to the Dao/Mapper interface above
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.kuang.dao.UserDao">
<!--   select:查询语句
        id:对应方法名
-->
<!--    resultType:返回一个结果
        resultMap:返回结果集
        后面的值要写全限定名:即包名+类名
-->
    <select id="getUserList" resultType="com.kuang.pojo.User">
        select * from user;
    </select>
    <select id="getUserById" resultType="com.kuang.pojo.User" parameterType="Integer">
        select * from user where id=#{
    
    id}
    </select>
<!--添加一个用户-->
    <insert id="addUser" parameterType="com.kuang.pojo.User" >
        insert into user (id,name,pwd) value (#{
    
    id},#{
    
    name},#{
    
    pwd})
    </insert>
<!--    删除一个用户-->
    <delete id="deleteUser" parameterType="Integer">
        delete from user where id=#{
    
    id}
    </delete>
    
<!--    修改用户信息-->
    <update id="updateUser" parameterType="com.kuang.pojo.User">
        update user set name=#{
    
    name} ,pwd=#{
    
    pwd} where id= #{
    
    id}
    </update>
</mapper>

insert image description here

6. Write test classes

package com.kuang.dao;

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

import java.util.List;

public class UserDaoTest {
    
    
    @Test
    public void test(){
    
    
        //第一步:获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //执行Sql
//        方式一:getMapper(推荐使用)
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();


//       方式二:
//        List<User> userList = sqlSession.selectList("com.kuang.dao.UserDao.getUserList");


        for (User user:userList) {
    
    
            System.out.println(user);
        }

        //关闭sqlSession
        sqlSession.close();
    }
    @Test
    public void testGetUserById(){
    
    
        //第一步:获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //执行Sql
//        方式一:getMapper(推荐使用)
        UserDao userDao = sqlSession.getMapper(UserDao.class);

        User user1 = userDao.getUserById(1);
        System.out.println(user1);


        //关闭sqlSession
        sqlSession.close();
    }
//  增删改需要提交事务
    @Test
    public void addUser(){
    
    
        //第一步:获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User user1 = new User();
        user1.setId(13);
        user1.setName("小新");
        user1.setPwd("123456");
        Integer isSuccess = userDao.addUser(user1);
        System.out.println(isSuccess);
        if(isSuccess>0){
    
    
            System.out.println("success");
//            提交事务
            sqlSession.commit();
        }else {
    
    
            System.out.println("errror");
        }


        //关闭sqlSession
        sqlSession.close();
    }

    @Test
    public void deleteUser(){
    
    
        //第一步:获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();

//        执行sql
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        Integer tag = userDao.deleteUser(12);
        if (tag>0){
    
    
            System.out.println("删除成功");
            sqlSession.commit();
        }else {
    
    
            System.out.println("删除失败");
        }


        //关闭sqlSession
        sqlSession.close();
    }

    @Test
    public void updateUser(){
    
    
        //第一步:获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();

//        执行sql
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User user1 = new User();
        user1.setId(12);
        user1.setName("小新");
        user1.setPwd("123456");
        Integer tag = userDao.updateUser(user1);
        if (tag>0){
    
    
            System.out.println("更新成功");
            sqlSession.commit();
        }else {
    
    
            System.out.println("更新失败");
        }


        //关闭sqlSession
        sqlSession.close();
    }
}

insert image description here

 @Test
    public void test(){
    
    
        //第一步:获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //执行Sql
//        方式一:getMapper(推荐使用)
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        调用接口方法
        List<User> userList = userDao.getUserList();

        //关闭sqlSession
        sqlSession.close();
    }

Guess you like

Origin blog.csdn.net/Silly011/article/details/124073759