IDEA+Maven uses MyBatis to realize CRUD operation (the content is detailed, and the 10000 word long article will take you to know MyBatis ~)

IDEA+Maven uses MyBatis to implement CRUD operation

Hello, everyone. Today, I'm going to use Maven to build MyBatis project in IDEA to realize simple operations of addition, deletion, modification and query,

After summarizing some experiences of bloggers in the learning process, let's enter the construction project

Introduction to MyBatis

MyBatis is an excellent persistence layer framework, which supports custom SQL, stored procedures and advanced mapping. MyBatis eliminates almost all JDBC code and the work of setting parameters and obtaining result sets. MyBatis can configure and map primitive types, interfaces and Java POJO s (Plain Old Java Objects) to records in the database through simple XML or annotations.

- > excerpted from MyBatis official website

Why use MyBatis

First of all, JDBC was used to realize the CRUD operation of the database. It is too troublesome to splice SQL statements, and the code is easy to make mistakes, which greatly reduces the development efficiency

Using MyBatis to realize CRUD operation greatly improves the development efficiency. As an excellent persistence layer framework, MyBatis greatly reduces the splicing of SQL statements, improves the readability of the code and is easy to maintain. MyBatis uses the interface corresponding to XML file to realize CRUD operation on the data base.

New Maven project

File --> New —> Project

As follows:

Click Next

Click Finish to complete the Maven project creation

Note: when Maven builds a project, you need to see whether the path pointed to by Maven is a local path

File --> setting --> Build,Exception,Eeployment --> Build Tools --> Maven

After configuration, click Apply to agree and OK to confirm

Configure POM XML file

<dependencies>
<!--        mysql drive-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
<!--        mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.4</version>
        </dependency>
<!--        junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
            <resource>
                <directory>libs/</directory>
                <targetPath>libs</targetPath>
                <includes>
                    <include>**/*.jar</include>
                </includes>
            </resource>
        </resources>
    </build>

Project structure

Database preparation

Create a new database mybatis, data table user

CREATE DATABASE mybatis;
USE mybatis;
CREATE TABLE `user` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) DEFAULT NULL,
  `password` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

resources - > New - > file named dB Properties configuration database information

db.properties file

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1/mybatis?useSSL=true
username=root
password=111111

MyBatis core profile

resources - > New - > file is named mybatis config xml

Note: click refresh to download the configuration file from the remote warehouse to the local warehouse

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>

<!--    Import database configuration information-->
    <properties resource="db.properties"/>
    <settings>
        <!--        Standard log factory implementation-->
        <setting name="logImpl" value="StDOUT_LOGGING"/>
        <!--        <setting name="logImpl" value="LOG4J"/>-->
    </settings>
    <typeAliases>
        <package name="com.wanshi.bean"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driverClassName}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--    Register interface-->
    <mappers>
        <mapper resource="com/wanshi/mapper/UserMapper.xml"></mapper>
    </mappers>
</configuration>

Write source code

Create the following project structure

MyBatis tool class

Write the MyBatisUtils class

package com.wanshi.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;

public class MyBatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resources = "mybatis-config.xml";
            //Encapsulate the mybatis core configuration file into an input stream
            InputStream in = Resources.getResourceAsStream(resources);
            //SqlSessionFactoryBuilder builds the input stream and compiles it into sqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * sqlSessionFactory Construct and return a SqlSession for database CRUD operation
     * @return
     */
    public SqlSession getSession() {
        return sqlSessionFactory.openSession();
    }
}

Entity class

Write User class

package com.wanshi.bean;

public class User {

    private Integer id;
    private String name;
    private Integer password;

    public User() {
    }

    public User(Integer id, String name, Integer password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Integer getPassword() {
        return password;
    }

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

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

mapper interface and xml file writing

Write UserMapper interface

package com.wanshi.mapper;

import com.wanshi.bean.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UserMapper {

    /**
     * Query all users
     * @return
     */
    List<User> getUserList();

    /**
     * Query a user information according to the user id
     * @param id
     * @return
     */
    User getByUserId(@Param("uid") Integer id);

    /**
     * Add a user
     * @param user
     * @return
     */
    Integer add(User user);

    /**
     * Modify a user information
     * @param user
     * @return
     */
    Integer update(User user);

    /**
     * Delete a user according to the user id
     * @param id
     * @return
     */
    Integer delete(@Param("uid") Integer id);
}

UserMapper.xml

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

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

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

    <insert id="insert" parameterType="user">
        insert into user (name, password) values(#{name}, #{password})
    </insert>

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

    <delete id="delete" parameterType="int">
        delete from user where id = #{uid}
    </delete>
</mapper>

Connect to database in IDEA

Click the DataSource option on the right to connect to the database

Click+

Select DataSource - > mysql

Click apply to agree and click ok. The connection is successful, as shown in the following page

test

Create a new test class, TestUser, which is implemented by Junit unit test

package com.wanshi.test;

import com.wanshi.bean.User;
import com.wanshi.mapper.UserMapper;
import com.wanshi.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class TestUser {

    @Test
    public void getUserList() {
        SqlSession sqlSession = MyBatisUtils.getSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userMapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        sqlSession.close();
    }

    @Test
    public void getByUserId() {
        SqlSession sqlSession = MyBatisUtils.getSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.getByUserId(1);
        System.out.println(user);
        sqlSession.close();
    }

    @Test
    public void insert() {
        SqlSession sqlSession = MyBatisUtils.getSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = new User();
        user.setName("admin");
        user.setPassword(1234);
        Integer i = userMapper.insert(user);
        System.out.println(i);
        //    Note: add, delete and modify operations need to start the transaction manually, otherwise they cannot be executed
        if (i > 0) {
            sqlSession.commit();
        }
        sqlSession.close();
        
    }

    @Test
    public void update() {
        SqlSession sqlSession = MyBatisUtils.getSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        Integer i = userMapper.update(new User(3, "Li San", 123445));
        System.out.println(i);
        //    Note: add, delete and modify operations need to start the transaction manually, otherwise they cannot be executed
        if (i > 0) {
            sqlSession.commit();
        }
        sqlSession.close();
    }

    @Test
    public void delete() {
        SqlSession sqlSession = MyBatisUtils.getSession();

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        Integer i = userMapper.delete(2);
        System.out.println(i);
        //    Note: add, delete and modify operations need to start the transaction manually, otherwise they cannot be executed
        if (i > 0) {
            sqlSession.commit();
        }
        sqlSession.close();
    }

}

test result

Query all users

Query the specified user according to the user id

Add user

Modify user

delete user

epilogue

Mybatis's entry-level addition, deletion, modification and query operation is over. There must be no problem in program execution. If you encounter problems, you can leave a message in the comment area. See you next, mybatis series articles!

Keywords: Java Maven Mybatis IDEA

Added by lifeless on Mon, 20 Dec 2021 05:41:29 +0200