Mybatis adds, deletes, changes and checks quickly! ! !


Introduction to Mybatis
**

1. What is Mybatis

**

MyBatis is an excellent Java-based persistence layer framework, which
encapsulates jdbc internally , so that developers only need to pay attention to the sql statement itself.

Reference document: https://mybatis.org/mybatis-3/zh/index.html

2. Persistence
Data persistence.
Persistence is the process of converting the data of the program between the persistent state and the transient state
. Memory: Lost when power is off
. Database (jdbc), io file persistence.
Persistence encountered in life: The meat we bought will be broken if it is left for too long, so we need to put the meat in the refrigerator and defrost it when we eat it.

3. Persistence layer
Dao layer, Service layer, Controller layer...
·The code block to complete the persistence work
·The layer boundary is very clear
CRUD

1. Build the environment

-[] 1. Build a database

CREATE DATABASE mybatis;

USE mybatis;

CREATE TABLE user(
id int(20) NOT NULL PRIMARY KEY,
name varchar(30) DEFAULT NULL,
pwd varchar(20) DEFAULT NULL
);

INSERT INTO user(id,name,pwd) VALUES
(1,'李李李','123456'),
(2,'华晨宇','666666'),
(3,'苑苑苑','520520');

2.pom.xml
·Create a new ordinary maven project

·Delete the src directory

3. Import maven dependency pom.xml

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
    <version>1.18.18</version>
    </dependency>
</dependencies>

3.CRUD

4. Create a module

· Write the core configuration file mybatis-config.xml of mybatis

<?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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>  <!-- ?useSSL=false-->
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="UserDao.xml"/>
    </mappers>
</configuration>

·Write mybatis tool class MybatisUtils

public class MybatisUtils {//使用mybatis的第一步:获取sqlSessionFactory对象
    //    private static SqlSessionFactory factory = null;
    private static SqlSessionFactory sqlSession;
    static {
        try {
    //使用mybatis第一步、获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSession = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession(){
        return sqlSession.openSession();
    }
}

Write code

·Entity User

import lombok.Data;

@Data
public class User {
    private Integer id;
    private String name;
    private String pwd;

    public User() {
    }

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

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

· Dao interface UserDao

//这个类操作对象的实体
package com.guohui.dao;
import com.guohui.pojo.User;
import java.util.List;

public interface UserDao {
     //查询所有用户
     List<User> getUserList();
     //根据id查询用户
     User getUserById(int id);
     //添加一个用户
     int addUser(User user);
     //修改用户
     int updateUser(User user);
     //根据id删除用户
     int deleteUser(int id);
}

·Interface implementation class UserDao.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">
<!--namespace=绑定对应的Dao/mapper接口-->
<mapper namespace="com.guohui.dao.UserDao">
    <!--select查询语句-->
    <select id="getUserList" resultType="com.guohui.pojo.User">
        select * from user
    </select>
<!--    根据id查询用户-->
    <select id="getUserById" parameterType="int" resultType="com.guohui.pojo.User">
        select * from user where id = #{id}
    </select>
<!--    添加一个用户-->
    <insert id="addUser" parameterType="com.guohui.pojo.User">
        insert into user(id, name, pwd) values (#{id},#{name},#{pwd})
    </insert>
<!--    修改用户-->
    <update id="updateUser" parameterType="com.guohui.pojo.User">
        update user set name=#{name},pwd=#{pwd} where id = #{id}
    </update>
<!--    删除用户-->
    <delete id="deleteUser" parameterType="int">
        delete from user where id = #{id}
    </delete>
</mapper>

·Test.junit test

public class MyTest {

    @Test
    public void test(){//查询全部用户
        //第一步:获得SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //执行SQL
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> userList = mapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        //关闭SqlSession
        sqlSession.close();
    }
    @Test//查询id用户
    public void test01(){
        //根据id查询用户
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        //查询id为1 的用户
        User user = mapper.getUserById(1);
        System.out.println(user);

        sqlSession.close();
    }
    @Test//添加用户
    public void addUser(){
        //添加一个用户
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserDao mapper = sqlSession.getMapper(UserDao.class);

        User user = new User(9,"苑雪儿","guohui520");
        int i = mapper.addUser(user);
        System.out.println("插入成功"+i);
        sqlSession.commit(); //提交事务,重点!不写的话不会提交到数据库
        sqlSession.close();
    }
    @Test//修改用户
    public void updateUser(){
        //添加一个用户
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserDao mapper = sqlSession.getMapper(UserDao.class);

        mapper.updateUser(new User(5,"李国辉","520yuanxueer"));
        System.out.println("修改成功!");
        sqlSession.commit(); //提交事务,重点!不写的话不会提交到数据库
        sqlSession.close();
    }
    @Test//删除用户
    public void testDeleteUser() {
        SqlSession session = MybatisUtils.getSqlSession();
        UserDao mapper = session.getMapper(UserDao.class);
        int i = mapper.deleteUser(5);
        System.out.println(i);
        session.commit(); //提交事务,重点!不写的话不会提交到数据库
        session.close();
    }
}

Thank you for watching. If you have any questions, you can comment and modify it online at any time.

Guess you like

Origin blog.csdn.net/weixin_45967375/article/details/115066330