Use the MyBatis framework to realize the addition, full check, single check, modification, and deletion of forms

 1. What is the MyBatis framework

It is a semi-automatic ORM persistence layer framework with high SQL flexibility, supports advanced mapping (one-to-one, one-to-many), dynamic SQL, lazy loading and caching, etc., but its database independence is low

What are ORMs?

Object Relation Mapping, object relational mapping. The object refers to the Java object, and the relationship refers to the relational model in the database. Object-relational mapping refers to establishing a correspondence between the Java object and the relational model of the database, such as using a Java Student class to correspond A student table in the database, the attributes in the class correspond to the columns in the table. The Student class corresponds to the student table, and a Student object corresponds to a row of data in the student table.

Why is mybatis a semi-automatic ORM framework?

To develop with mybatis, you need to manually write SQL statements. And a fully automatic ORM framework, such as hibernate, does not need to write SQL statements. Developed with hibernate, you only need to define the ORM mapping relationship, and then you can directly perform CRUD operations. Because mybatis needs to write SQL statements by hand, it has high flexibility, and can freely customize SQL according to needs, and because it is necessary to write SQL by hand, when switching databases, SQL statements may need to be rewritten, because different The database has different dialects (Dialect), so the database independence of mybatis is low. Although mybatis needs to write SQL by hand, compared with JDBC, it provides input mapping and output mapping, which can easily set SQL parameters and encapsulate the result set. And it also provides functions such as relational query and dynamic SQL, which greatly improves the efficiency of development. And its learning cost is much lower than hibernate.

2. How to use mybatis

1. Create a database

#判断存在即删除数据库
drop database if exists mydb;
#创建数据库
create database mydb;
#使用数据库
use mydb;


#创建表
create table t_user
(
	uid int primary key auto_increment,
	username varchar(20),
	password varchar(20),
	phone varchar(11),
	address varchar(50)
);


insert into t_user(username,password,phone,address) values('张三','666','18965423548','南阳');
insert into t_user(username,password,phone,address) values('李四','333','18754263548','许昌');
insert into t_user(username,password,phone,address) values('小美','123','18565234759','信阳');

2. Create a Java project and import the jar package of the mybatis framework

3. Create an entity class corresponding to the table

public class User {
    private Integer uid;
    private String userName;
    private String password;
    private String phone;
    private String address;

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

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

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                ", phone='" + phone + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

4. Create an interface class for table operations

public interface UserInterface {
    //全查
    List<User> selectAll();
    //添加
    int add(User user);
    //删除
    int dell(int uid);
    //修改
    int update(User user);
    //单查
    User select(int uid);
    //模糊查询
    List<User> mohu(String name);
}

5. Create a properties file in the src folder 

 Create the jdbc.properties file (the steps are shown in the figure above):

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mydb
username=root
password=root

Introduce the log file log4j.properties:

log4j.rootLogger=TRACE,stdout  

log4j.appender.stdout=org.apache.log4j.ConsoleAppender   
#log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout   


log4j.appender.logfile=org.apache.log4j.FileAppender   
log4j.appender.logfile.File=wocao.log   
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout   
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n   
log4j.logger.mapperNS =TRACE

log4j.logger.com.mybatis=DEBUG  
log4j.logger.com.mybatis.common.jdbc.SimpleDataSource=DEBUG   
log4j.logger.com.mybatis.common.jdbc.ScriptRunner=DEBUG   
log4j.logger.com.mybatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG   
log4j.logger.java.sql.Connection=DEBUG  
log4j.logger.java.sql.Statement=DEBUG  
log4j.logger.java.sql.PreparedStatement=DEBUG  
log4j.logger.java.sql.ResultSet=DEBUG  

log4j.logger.org.springframework=error 
log4j.logger.org.apache=ERROR  
log4j.logger.org.mybatis=DEBUG 

6. Create the corresponding mapper mapping configuration file in the interface package

<?xml version="1.0" encoding="UTF-8"?>
<!--声明XML文档的版本和编码-->
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--声明文档类型,这里使用MyBatis映射文件的DTD-->
<!--namespace是映射的dao接口-->
<mapper namespace="com.liu.dao.UserInterface">

    <!--查询所有用户-->
    <select id="selectAll" resultType="user">
        select * from t_user;
    </select>

    <!--添加用户-->
    <insert id="add" parameterType="user">
        insert into t_user(username,password,phone,address) values(#{userName},#{password},#{phone},#{address});
    </insert>

    <!--删除用户-->
    <delete id="dell" parameterType="user">
        delete from t_user where uid=#{uid}
    </delete>

    <!--更新用户-->
    <update id="update" parameterType="user">
        update t_user set username=#{userName},password=#{password},phone=#{phone},address=#{address} where uid=#{uid};
    </update>

    <!--根据id查询用户-->
    <select id="selectById" resultType="user" parameterType="int">
        select * from t_user where uid=#{uid};
    </select>

    <!--模糊查询用户-->
    <select id="mohu" resultType="user" parameterType="string">
        select * from t_user where username like concat ('%',#{name},'%')
    </select>
</mapper>

7. Create the core configuration file of the mybatis framework in the src directory

<?xml version="1.0" encoding="UTF-8"?>
<!--声明XML文档的版本和编码-->
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--声明文档类型,这里使用MyBatis配置文件的DTD-->
<configuration>

    <!--引入JDBC配置文件-->
    <properties resource="jdbc.properties"/>

    <!--MyBatis全局配置-->
    <settings>
        <!--日志实现方式-->
        <setting name="logImpl" value="log4j"/>
    </settings>

    <!--类型别名-->
    <typeAliases>
        <!--扫描指定包下的Java Bean,将类名作为别名-->
        <package name="com.liu.bean"/>
    </typeAliases>

    <!--数据库环境配置-->
    <environments default="mysql">
        <!--指定数据库环境id-->
        <environment id="mysql">
            <!--事务管理器类型-->
            <transactionManager type="jdbc"></transactionManager>
            <!--数据源类型-->
            <dataSource type="pooled">
                <!--数据库驱动-->
                <property name="driver" value="${driver}"/>
                <!--数据库URL-->
                <property name="url" value="${url}"/>
                <!--数据库用户名-->
                <property name="username" value="${username}"/>
                <!--数据库密码-->
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--映射器配置-->
    <mappers>
        <!--指定映射器接口的全限定名-->
        <mapper class="com.liu.dao.UserInterface"></mapper>
    </mappers>
</configuration>

8. Test in the test class

import com.liu.bean.User;
import com.liu.dao.UserInterface;
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.List;
import java.util.Scanner;


// 定义一个名为UserTest的类
public class UserTest {
    // 声明一些需要在测试中使用的变量,这些变量可以在@Before和@After中被初始化和关闭
    InputStream stream = null;
    SqlSessionFactoryBuilder builder = null;
    SqlSessionFactory factory = null;
    SqlSession sqlSession = null;
    UserInterface userInterface = null;

    // 在所有测试方法运行之前运行的方法,用于初始化测试所需的变量
    @Before
    public void aaaa() throws IOException {
        // 从SqlMapConfig.xml配置文件中获取数据库连接信息的输入流
        stream = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 创建SqlSessionFactoryBuilder实例,用于创建SqlSessionFactory实例
        builder = new SqlSessionFactoryBuilder();
        // 通过SqlSessionFactoryBuilder实例的build方法创建SqlSessionFactory实例
        factory = builder.build(stream);
        // 通过SqlSessionFactory实例创建SqlSession实例
        sqlSession = factory.openSession();
        // 获取UserInterface实例
        userInterface = sqlSession.getMapper(UserInterface.class);
    }

    // 测试查询所有用户的方法
    @Test
    public void testSelectAll() {
        // 调用UserInterface实例的selectAll方法查询所有用户,并将结果存储在userList中
        List<User> userList = userInterface.selectAll();
        // 遍历userList并输出每个用户
        for (User user : userList) {
            System.out.println(user);
        }
    }

    // 测试添加用户的方法
    @Test
    public void testadd() {
        // 创建一个新的User实例,并设置其属性值
        User user = new User();
        user.setUserName("wzl");
        user.setPassword("123");
        user.setPhone("12345678901");
        user.setAddress("安阳");
        // 调用UserInterface实例的add方法将新用户添加到数据库,并将受影响的行数存储在add变量中
        int add = userInterface.add(user);
        // 如果成功添加了用户,则查询并输出所有用户
        if (add > 0) {
            List<User> userList = userInterface.selectAll();
            for (User user1 : userList) {
                System.out.println(user1);
            }
        }
    }

    // 测试删除用户的方法
    @Test
    public void testdell() {
        // 定义要删除的用户的id
        int uid = 11;
        // 调用UserInterface实例的dell方法删除指定id的用户,并将受影响的行数存储在dele变量中
        int dele = userInterface.dell(uid);
        // 如果成功删除了用户,则查询并输出所有用户
        if (dele > 0) {
            List<User> userList = userInterface.selectAll();
            for (User user1 : userList) {
                System.out.println(user1);
            }
        }
    }

    // 测试更新用户的方法
    @Test
    public void testupdate() {
        // 通过id查询用户并输出
        User select = userInterface.selectById(10);
        System.out.println("修改前" + select);
        // 构造新的User对象并更新用户信息
        User user = new User();
        user.setUid(10);
        user.setUserName("王二麻子");
        user.setPassword("12345");
        user.setPhone("12345678901");
        user.setAddress("平顶山");
        int update = userInterface.update(user);
        // 如果成功更新用户,则通过id再次查询用户并输出
        if (update > 0) {
            User select2 = userInterface.selectById(10);
            System.out.println("修改后" + select2);
        }
    }

    // 测试通过id查询用户的方法
    @Test
    public void testselectById() {
        // 定义要查询的用户的id
        int uid = 1;
        // 调用UserInterface实例的selectById方法查询指定id的用户并输出
        User select = userInterface.selectById(1);
        System.out.println(select);
    }

    // 测试模糊查询用户的方法
    @Test
    public void testmohu() {
        // 通过键盘输入获取模糊查询关键字
        Scanner sc = new Scanner(System.in);
        String aa = sc.next();
        // 调用UserInterface实例的mohu方法模糊查询用户并输出
        List<User> mohu = userInterface.mohu(aa);
        for (User user : mohu) {
            System.out.println(user);
        }
    }
     // 执行测试后的善后处理

    @After
    public void bbb() throws IOException {
        // 提交事务
        sqlSession.commit();
        // 关闭输入流
        if (stream != null) {
            stream.close();
        }
        // 关闭sqlSession
        if (sqlSession != null) {
            sqlSession.close();
        }
    }
}

operation result

Full check results:

 Add running results:

Delete run results:

Modify the running result:

Single check run results:

Fuzzy query results:

 

Guess you like

Origin blog.csdn.net/weixin_69420643/article/details/129449619