Mybatis - the first Mybatis program

The first Mybatis program

Ideas: build the environment -> import Mybatis -> write code -> test

1. Build the environment

1.1 Build the database

(1) Create a new database - mybatis
(2) Create a new user table in the mybatis database

create table `user`(
	`id` int(20) not null ,
	`name` varchar(30) default null,
	`pwd` varchar(30) default null,
	primary key(`id`)
)engine=INNODB default  charset=utf8;

insert into `user` (`id`,`name`,`pwd`) values
(1,'婉婉','1123'),
(2,'小红','1123'),
(3,'晓晓','1123')

insert image description here

1.2 New project

insert image description here
insert image description here
insert image description here
Change the maven warehouse address: modify the location of the maven warehouse in the idea
insert image description here

1.3 delete src

insert image description here
insert image description here

1.4 Import dependencies

  <!--mysql驱动        -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
        </dependency>
        <!--mybatis        -->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>
        <!--junit        -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

insert image description here
If the version is red, just click maven on the right and refresh
insert image description here

1.5 Create a new model

insert image description here

1.6 Connecting to the database

1. Open the database
insert image description here
2. Click the database on the right side of the idea
insert image description here
insert image description here

1.7 Writing configuration files

Create a configuration file of mybatis-config.xml under the resource under the project
insert image description here

url:数据库连接地址
                    useSSL=false 安全连接,只有当由安全证书时才能用true
                    useUnicode=true  Unicode编码
                    characterEncoding=UTF-8   字符为UTF-8格式
                    serverTimezone=GMT    设置时区
                    &符要用转义字符&amp;
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuratio是核心配置文件-->
<configuration>
    <environments default="development">
        <environment id="development">
<!--            transactionManager:事务管理-->
            <transactionManager type="JDBC"/>
<!--            dataSource中包含数据库相关配置-->
            <dataSource type="POOLED">
<!--               driver:数据库驱动com.mysql.jdbc.Driver -->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
<!--                url:数据库连接地址
                    useSSL=false 安全连接,只有当由安全证书时才能用true
                    useUnicode=true  Unicode编码
                    characterEncoding=UTF-8   字符为UTF-8格式
                    serverTimezone=GMT    设置时区
                    &符要用转义字符&amp;
                    -->
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useEncoding=false&amp;characterEncoding=UTF-8&amp;serverTimezone=GMT"/>
<!--               username:用户名-->
                <property name="username" value="root"/>
<!--                password:数据库连接密码-->
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
<!--    每个Mapper.xml都需要在Mybatis核心配置文件中注册-->
    <mappers>
        <mapper resource="com/kuang/dao/UserMapper.xml"/>
    </mappers>

</configuration>

1.8 Write mybatis tool class

1. Create a new package com.kuang.dao and com.kuang.utils
insert image description here
insert image description here
insert image description here

1.9 Write mybatis tool class

Create a new tool class MybatisUtils under the com.kuang.utils package

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

//sqlSessionFactory用来构建sqlSession
public class MybatisUtils {
    
    

    //提升SqlSessionFactory的作用域
    private static SqlSessionFactory sqlSessionFactory;

    static{
    
    
        try {
    
    
//            使用Mybatis第一步获取sqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch (IOException e){
    
    
            e.printStackTrace();
        }
    }
//    既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
//    SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
    public static SqlSession getSqlSession(){
    
    
       return sqlSessionFactory.openSession();

    }
}

1.10 Writing code

  • entity class
    insert image description here
package com.kuang.pojo;

//实体类对象
public class User {
    
    
    private int id;
    private String name;
    private String pwd;

    public int getId() {
    
    
        return id;
    }

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

    public String getName() {
    
    
        return name;
    }

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

    public String getPwd() {
    
    
        return pwd;
    }

    public void setPwd(String pwd) {
    
    
        this.pwd = pwd;
    }

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

  • Dao interface
    insert image description here
package com.kuang.dao;

import com.kuang.pojo.User;

import java.util.List;

public interface UserDao {
    
    

//    返回所有用户信息
    List<User> getUserList();
}

  • The implementation class of the Dao interface is
    converted from the original UserDaoImpl to a Mapper configuration file
    insert image description here
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.kuang.dao.UserDao">
<!--   select:查询语句
        id:对应方法名
-->
<!--    resultType:返回一个结果
        resultMap:返回结果集
        后面的值要写全限定名:即包名+类名
-->
    <select id="getUserList" resultType="com.kuang.pojo.User">
        select * from user;
    </select>
</mapper>

1.11 Testing

junit test

package com.kuang.dao;

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

import java.util.List;

public class UserDaoTest {
    
    
    @Test
    public void test(){
    
    
        //第一步:获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //执行Sql
//        方式一:getMapper(推荐使用)
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();

//       方式二:
//        List<User> userList = sqlSession.selectList("com.kuang.dao.UserDao.getUserList");


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

        //关闭sqlSession
        sqlSession.close();
    }
}


insert image description here

result

insert image description here

Guess you like

Origin blog.csdn.net/Silly011/article/details/124046175