Introductory learning of Mybatis

1. What is a framework

 Framework is a reusable design of the whole or part of the system, represented by a set of abstract components and methods of interaction between component instances;

Another definition holds that a framework is an application skeleton that can be customized by application developers.

2. Problems to be solved by the framework

The most important problem that the framework needs to solve is the problem of technology integration. In the J2EE framework, there are various technologies. Different software companies need to choose different technologies from J2EE, which makes the software companies ultimately Applications rely on these technologies, and the complexity of the technology itself and the discoverability of the technology will have an impact on the applications. 

 2.1 Key points

 *MyBatis core object

*Detailed explanation of core configuration files

*Configuration file completes CRUD operations

 

 3. Create a test 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','信阳');
select * from t_user;

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

Create a lib folder in the project, put the jar package of the mybatis framework, and import it into the project.

5. Create an entity class corresponding to the table

Create the com.fu.bean package in src, and then create the User entity class.

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

6. Create an interface class for table operations.

Create the com.fu.dao package in src, then create the UserDao interface, and then define additions and deletions for the database in the interface

Change and check operations.

public interface UserDao {
    //数据库的查询
    List<User> selectAll();
    //数据库的添加
    int add(User user);
    //数据库的删除
    int delete(int uid);
    //数据库的修改
    int update(User user);
}

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

Create a configuration file with the same name as the interface in the same directory as the dao interface.

<?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 namespace="com.fu.dao.UserDao">
    <!--通过select标签进行查询
        id:映射接口的方法名
        parameterType:指定参数的类型(如果是集合类型只需要指定集合元素的类型即可)
        resultType:指定返回值的类型-->
    <select id="selectAll" resultType="com.fu.bean.User">
    select * from t_user;
    </select>
    <!--通过insert标签进行添加
        id:映射接口的方法名
        parameterType:指定参数的类型(如果是集合类型只需要指定集合元素的类型即可)
        resultType:指定返回值的类型-->
    <insert id="add" parameterType="com.fu.bean.User">
    insert into t_user(username,password,phone,address) values(#{username},#{password},#{phone},#{address});
    </insert>
    <!--通过delete标签进行删除
        id:映射接口的方法名
        parameterType:指定参数的类型(如果是集合类型只需要指定集合元素的类型即可)
        resultType:指定返回值的类型-->
    <delete id="delete" parameterType="int">
        delete from t_user where uid=#{uid}
    </delete>
    <!--通过update标签进行修改
        id:映射接口的方法名
        parameterType:指定参数的类型(如果是集合类型只需要指定集合元素的类型即可)
        resultType:指定返回值的类型-->
    <update id="update" parameterType="com.fu.bean.User">
        update t_user set username=#{username},password=#{password},phone=#{phone},address=#{address} where uid=#{uid}
    </update>
</mapper>

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

Create a file in src, named SqlMapConfig.xml, and configure the parameters for connecting to the database in the configuration file.

<?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>
    <!--配置环境信息===就是配置连接数据库的参数
        default:指定配置的环境信息的id,表示默认连接该环境
         -->
    <environments default="mysql">
        <environment id="mysql">
            <!--配置事务的处理方式:模式使用JDBC的事务处理-->
            <transactionManager type="jdbc"></transactionManager>
            <!--数据源的默认type设置为pooled,表示使用连接池-->
            <dataSource type="pooled">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mydb"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--加载mapper配置文件-->
    <mappers>
        <mapper class="com.fu.dao.UserDao"></mapper>
    </mappers>
</configuration>

9. Test in test class

package com.fu.test;
 
import com.fu.bean.User;
import com.fu.dao.UserDao;
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.Test;
 
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
 
public class UserText {
    @Test
    public void testSelectAll() throws IOException {
        //1.加载核心配置文件的字节输入流
        InputStream stream = Resources.getResourceAsStream("mybatis.xml");
        //2.创建SqlSessionFactory的构建对象--框架使用的是构建者模式
        SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
        //3.通过构建对象加载配置文件的输入流获取SqlSessionFactory
        SqlSessionFactory factory=builder.build(stream);
         //4.通过工厂对象获取SqlSession对象----执行JDBC操作的
        SqlSession sqlSession=factory.openSession();
        //5.通过SqlSession对象获取接口对应的代理对象
        UserDao userDao=sqlSession.getMapper(UserDao.class);
        //6.通过代理对象执行查询方法
        List<User> userList = userDao.selectAll();
        //7.遍历集合
        for (User user : userList) {
            System.out.println(user);
        }
    }
    @Test
    public void testAddAll() throws IOException {
        InputStream stream= Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(stream);
        SqlSession sqlSession = factory.openSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        User user=new User();
        user.setUsername("李四");
        user.setPassword("123");
        user.setPhone("111");
        user.setAddress("ssss");
        int a = userDao.add(user);
        if(a>0){
            System.out.println("添加成功");
        }
        else{
            System.out.println("添加失败");
        }
 
    }
    @Test
    public void testdeleteAll() throws IOException {
        InputStream stream= Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(stream);
        SqlSession sqlSession = factory.openSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
 
        int a = userDao.delete(6);
        if(a>0){
            System.out.println("删除成功");
        }
        else{
            System.out.println("删除失败");
        }
 
    }
    @Test
    public void testupdateAll() throws IOException {
        InputStream stream= Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(stream);
        SqlSession sqlSession = factory.openSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
 
        User user=new User();
        user.setUid(2);
        user.setUsername("xxx");
        user.setPassword("xxx");
        user.setPhone("xxx");
        user.setAddress("xxx");
 
        int a = userDao.update(user);
 
        if(a>0){
            System.out.println("修改成功");
        }
        else{
            System.out.println("修改失败");
        }
 
    }
}

Guess you like

Origin blog.csdn.net/WJY898989/article/details/129374682