This is the 20th day of my participation in the August Text Challenge.More challenges in August

preface

In the last article we covered persistence and an introduction to Mybatis. Today we will look at how to create a beginner instance of Mybatis and how to use Mybatis for CRUD.

Database preparation

  1. First, let’s create a database for the use of subsequent steps;
CREATE DATABASE test;
USE test;
Copy the code
  1. Next, create a table to store the data.
CREATE TABLE user (
	id int(20) NOT NULL AUTO_INCREMENT,
    name varchar(30) DEFAULT NULL,
    password varchar(30) DEFAULT NULL.PRIMARY KEY (id)
);
Copy the code
  1. Insert data into the database
INSERT INTO user (id, name, password) VALUES (1.Village Rain Yao.'123456'), (2.'Joe'.'1234567'), (3.'bill'.'12345678');
Copy the code

Creating a Maven project

  1. For details on how to create a Maven project, see my previous article: Building a Maven project with IDEA
  2. Then in the projectpom.xmlAdd MyBatis, MySQL, Junit dependency;
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>2.6.2</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.49</version>
</dependency>
<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.13</version>
	<scope>test</scope>
</dependency>
Copy the code

Write MyBatis instance

  1. Prepare MyBatis core configuration file inmain/resourcesNew Under Filemybatis-config.xmlTo configure the database.

      
<! DOCTYPEconfiguration
        PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url"
                          value="jdbc:mysql://localhost:3306/test? useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="12345"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>
Copy the code
  1. Write MyBatis utility class;
package com.cunyu.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;

/ * * *@author : cunyu
 * @version : 1.0
 * @className : MyBatisUtils
 * @date: 2020/7/14 though *@description: MyBatis utility class */

public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch(IOException e) { e.printStackTrace(); }}/ * * *@param
     * @return
     * @descriptionGet SqlSession connection *@date 2020/7/14 11:46
     * @author cunyu1943
     * @version1.0 * /
    public static SqlSession getSession(a) {
        returnsqlSessionFactory.openSession(); }}Copy the code
  1. Next, create the entity class;
package com.cun.pojo;

/ * * *@author : cunyu
 * @version : 1.0
 * @className : User
 * @date: 2020/7/14 now *@description: User Entity class */

public class User {
    private int id;
    private String name;
    private String password;

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

    public int getId(a) {
        return id;
    }

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

    public String getName(a) {
        return name;
    }

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

    public String getPassword(a) {
        return password;
    }

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

    @Override
    public String toString(a) {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\' ' +
                ", password='" + password + '\' ' +
                '} '; }}Copy the code
  1. Write Mapper interface;
package com.cunyu.dao;

import com.cunyu.pojo.User;

import java.util.List;

/ * * *@InterfaceName : UserDao
 * @Author : cunyu
 * @Date : 2020/7/14 13:49
 * @Version : 1.0
 * @Description: User interface **/

public interface UserDao {
    List<User> getUser(a);
}
Copy the code
  1. addUserMapper.xmlConfiguration file;

      
<! DOCTYPEmapper
        PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<! -- Bind Dao/Mapper interface -->
<mapper namespace="com.cunyu.dao.UserDao">
    <select id="getUser" resultType="com.cunyu.pojo.User">
        select * from user
    </select>
</mapper>
Copy the code
  1. Write test classes insrc/test/java/Keep the same directory structure under the directory, and then add a test class for testing;
package com.cunyu.dao;

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

import java.util.List;

/ * * *@author : cunyu
 * @version : 1.0
 * @className : UserDaoTest
 * @dateTherefore: 2020/7/14 *@description: UserDao interface test */

public class UserDaoTest {
    @Test
    public void test(a){
        // Get the SqlSession object
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        // Execute the SQL statement
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> userList = mapper.getUser();

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

        / / close the SqlSessionsqlSession.close(); }}Copy the code
  1. Running the test class yields the following results;

Query operationselect

Query users based on attributes

  1. inUserDaoTo add the corresponding method:
/ * * *@paramName User name *@returnUser object * corresponding to the user name@descriptionGet user * based on user name@date2020/7/14 any valiant man *@author cunyu1943
* @version1.0 * /
User getUserByName(String name);

/ * * *@param"Password," password *@returnThe user object corresponding to the password *@descriptionObtain the user object * based on the user password@date2020/7/14 to *@author cunyu1943  
* @version1.0 * /
User getUserByPassword(String password);
Copy the code
  1. Then, inUserMapper.xmladdSelectStatements. The meanings of each attribute are as follows:
  • Id: indicates the method name of the corresponding interface.
  • ResultType: return value of the SQL statement execution;
  • ParameterType: parameterType.
<select id="getUserById" resultType="com.cunyu.pojo.User">
    select * from user where id=#{id}
</select>

<select id="getUserByName" resultType="com.cunyu.pojo.User">
    select * from user where name=#{name}
</select>

<select id="getUserByPassword" resultType="com.cunyu.pojo.User">
    select * from user where password=#{password}
</select>
Copy the code
  1. Test in the test class;
@Test
public void testGetUserById(a) {
    // Execute the SQL statement
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    User user = mapper.getUserById(2);
    System.out.println(user);

    / / close the SqlSession
    sqlSession.close();
}

@Test
public void testGetUserByName(a) {
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    User user = mapper.getUserByName("Village Rain Yao");
    System.out.println(user);

    sqlSession.close();
}

@Test
public void testGetUserByPassword(a){
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    User user=mapper.getUserByPassword("123456");
    System.out.println(user);

    sqlSession.close();
}
Copy the code

The insertinsert

  1. First of all inUserDaoThe corresponding method is added to the interface
    / * * *@descriptionAdding a user@paramUser User object * to be added@return
    * @date2020/7/14 now *@author cunyu1943
    * @version1.0 * /
    int addUser(User user);
Copy the code
  1. inUserMapper.xmladdInsertStatements;
<insert id="addUser" parameterType="com.cunyu.pojo.User">
    insert into user(id, name, password) values (#{id},#{name},#{password})
</insert>
Copy the code
  1. Test in test method;
@Test
public void testAddUser(a) {
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    User user = new User(5."Rain"."6543210");
    int i = mapper.addUser(user);
    System.out.println(i);
    // Commit transaction to database
    sqlSession.commit();
    System.out.println("User added successfully");
    sqlSession.close();
}
Copy the code

Modify the operatingupdate

  1. inUserDaoAdd corresponding interfaces.
/ * * *@descriptionModify user * based on id@paramUser User object *@return
    * @date 2020/7/14 16:04
    * @author cunyu1943
    * @version1.0 * /
int updateUser(User user);
Copy the code
  1. inUserMapper.xmladdupdateStatements;
<update id="updateUser" parameterType="com.cunyu.pojo.User">
    update user set name=#{name},password=#{password} where id=#{id}
</update>
Copy the code
  1. Tests in test classes;
@Test
public void testUpdateUser(a){
    // Get the SqlSession object
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    User user = mapper.getUserById(1);
    user.setPassword("7891011");
    int i = mapper.updateUser(user);
    sqlSession.commit();
    System.out.println("Update data succeeded");
    sqlSession.close();
}
Copy the code

Delete operationdelete

  1. inuserDaoAdd interface to;
/ * * *@descriptionDeleting a user@paramUser User to be deleted *@return
    * @date2020/7/14 parts: *@author cunyu1943
    * @version1.0 * /
int deleteUserById(User user);
Copy the code
  1. inUserMapper.xmladddeleteStatements;
<delete id="deleteUserById" parameterType="com.cunyu.pojo.User">
    delete from user where id=#{id}
</delete>
Copy the code
  1. Test in a test class;
@Test
public void testDeleteUser(a){
    // Get the SqlSession object
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    User user = mapper.getUserById(5);
    int i = mapper.deleteUserById(user);
    sqlSession.commit();
    System.out.println("Data deleted successfully");
    sqlSession.close();
}
Copy the code

The last

The above is all of our content today, original is not easy, if you think my article is helpful to you, then help like attention, we will see you in the next article ~